无法在AppleScript中使用JavaScript执行JavaScript“document.getElementById('theID')。value ='item1';”

问题描述:

我无法在AppleScript编辑器中使用JavaScript使用以下代码段:无法在AppleScript中使用JavaScript执行JavaScript“document.getElementById('theID')。value ='item1';”

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这个词)

你说“出于某种原因,其他人得到了这个工作”,但是你得到了“Syntax Error Expected end of line,etc. but found identifier。”,所以很明显,如果你甚至无法在脚本编辑器中编译没有错误的话,那么绝对没有办法让任何人能够像Google Chrome一样使用该代码!

  1. do JavaScript语法是Safari浏览器,而不是谷歌Chrome浏览器。对于谷歌浏览器,它是execute javascript,但是更改不能修复您的代码。然后它错误地出现“Syntax Error Expected end of line,etc. but found class name”。并突出显示tab
  2. 如果你看看谷歌浏览器的AppleScript字典,它不支持current tab,它是active tab,并修复它并不能修复你的代码。然后它出错'AppleScript错误谷歌浏览器出现错误:无法将应用程序“谷歌浏览器”转换为类型说明符。并突出显示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"命令运行的代码下它可以在不为目标Web页面执行方面有完成加载,因此脚本可能失败的线条。

您需要添加相应的代码为它等待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 

当然,这并不意味着,一切工作都没有问题,并且您有责任根据需要添加适当的错误检查和处理。

+0

注意:虽然您有第一个窗口,但我将其更改为'front window'作为个人偏好,但与测试示例_code_无关,因为无论哪种方式都可以工作并产生相同的结果。 – user3439894