我不能使用以下代码片段在JavaScript编辑器中使用AppleScript:
在第一个窗口的当前选项卡中执行JavaScript "document.getElementById('theID').value =‘item1’“
tell application "Google Chrome"
open location "https://www.randomwebsite.com"
set theScript to "document.getElementById('term_input_id').value ='Spring 2015';"
do JavaScript theScript in current tab of first window
end tell
由于某些原因,其他人也会这样做,但请注意,这正是我想调用的javascript函数!
任何人都知道如何消除语法错误:行的预期结束,等等,但是找到了标识符。(AppleScript然后在上面的代码中高亮显示单词JavaScript )
发布于 2017-11-18 05:30:28
你说,“出于某种原因,其他人让它工作”,但你得到了“语法错误预期行尾等,但找到了标识符。”,所以很明显,如果你甚至不能让它编译没有错误的脚本编辑器,那么任何人都绝对不可能得到的代码,原来,在谷歌Chrome!
do JavaScript
语法是针对Safari的,而不是Google。对于Google来说,它是execute javascript
,但是修改它并不能修复您的代码。然后出错“语法错误,行尾等,但是找到了类名。”并高亮tab
。current tab
,它是active tab
,而修复它不能修复您的代码。然后用'AppleScript错误,Google得到了一个错误:无法将应用程序"Google“转换为specifier.‘类型。”并高亮execute javascript theScript in active tab of front window
。那么,接下来需要做什么才能让它不出错地编译呢?下面的重新处理代码具有从原始代码中进行的必要更改,以便在编译过程中不出错。
tell application "Google Chrome"
open location "https://www.randomwebsite.com"
set theScript to "document.getElementById('term_input_id').value = 'Spring 2015';"
execute active tab of front window javascript theScript
end tell
然而,仅仅因为可以在没有错误的情况下编译,并不一定意味着它可以在没有问题的情况下工作!
当open location "https://www.randomwebsite.com"
命令运行时,它后面的代码行可以执行,而不考虑目标网页已完成加载,因此脚本可能会失败。
您需要添加适当的代码,以等待open location ...
命令完成,然后再继续执行脚本的其余部分。
在互联网上搜索,你会找到各种方法来等待页面完成加载,然而,一个给定的方式与这个网站工作可能不适用于该网站。因此,您需要测试目标网站的工作原理。
与谷歌Chrome协同工作的一种通用方法是:
repeat until (loading of active tab of front window is false)
delay 0.2 -- # The value of the 'delay' command may be adjusted as appropriate.
end repeat
因此,您重新编写的代码现在看起来如下:
tell application "Google Chrome"
open location "https://www.randomwebsite.com"
repeat until (loading of active tab of front window is false)
delay 0.2
end repeat
set theScript to "document.getElementById('term_input_id').value = 'Spring 2015';"
execute active tab of front window javascript theScript
end tell
当然,这并不意味着所有事情都会顺利进行,您有责任在需要时添加适当的错误检查和处理。
https://stackoverflow.com/questions/47362315
复制