首页 > 解决方案 > 为什么 Automator AppleScript 不结束?

问题描述

好的,我意识到这个问题的解决方案可能非常简单,但我已经浪费了很多时间试图弄清楚。您可能会说,我是 AppleScript 的新手。

我有一个由 Automator 运行的 AppleScript。它单击 Chrome 中的一个按钮。我有一个动作需要重复近 1000 次,所以我正在尝试自动化它。这是我所拥有的:

tell application "Google Chrome"
    activate
    set theTab to tab 1 of window 1
    execute theTab javascript "document.querySelectorAll('[title=Archive]')[0].click()"
end tell

这可以按我的意愿工作:它会激活 Chrome 并单击活动选项卡上的按钮。单击该按钮会弹出一个警告框,默认为“确定”按钮。接下来我需要点击那个按钮,所以我有第二个 AppleScript:

tell application "Google Chrome" to activate
delay 2
tell application "System Events"
    keystroke return
end tell

让我明确一点:我知道最终我应该有一个脚本,但我创建了两个来诊断我遇到的问题。

看起来第一个脚本永远不会结束,所以它永远不会到达第二个脚本。如果我运行第一个脚本,停止它,然后运行第二个,我会得到我想要的。但除非我停止第一个脚本,否则它只会搅动,永远不会继续。虽然它正在执行 javascript,但它似乎只是停在那里。

就像我说的那样,这可能非常简单......而且我因为没有看到解决方案而感到非常愚蠢。我错过了什么?

标签: macosgoogle-chromeapplescriptautomator

解决方案


这并不像您想象的那么容易,因为带有“确定”按钮的警报框是模态的。这意味着:脚本将等待“确定”按钮被按下,然后才会继续。

我无法测试,因为我不使用谷歌浏览器,而且我不知道你测试的网页。自己试试我的建议(它使用了抛出人工干扰的想法):

tell application "Google Chrome"
    activate
    set theTab to tab 1 of window 1
    try
        with timeout of 1 second
         set theResult to (execute theTab javascript "document.querySelectorAll('[title=Archive]')[0].click()")
       end timeout
        theResult
    on error
        tell application "System Events" to keystroke return
    end try
end tell

我以编程方式关闭模式警报框对此进行了全面测试:

try
    with timeout of 1 second
        set theResult to display alert "TEST"
    end timeout
    theResult
on error
    tell application "System Events" to keystroke return
end try

推荐阅读