【问题标题】:Getting Active Window via Applescript throws error, "Can’t get window 1 of process"通过 Applescript 获取活动窗口会引发错误,“无法获取进程的窗口 1”
【发布时间】:2021-06-12 12:49:44
【问题描述】:

脚本:

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    tell process frontAppName
        tell (1st window whose value of attribute "AXMain" is true)
            set windowTitle to value of attribute "AXTitle"
        end tell
    end tell
end tell

return {frontAppName, windowTitle}

它有时有效,但有时我会得到类似:[2021-03-15 19:43:53.947] [error] Error: 339:344: execution error: System Events got an error: Can’t get window 1 of process "Adobe Premiere Pro 2020" whose value of attribute "AXMain" = true. Invalid index. (-1719)

有什么想法吗?

谢谢!

【问题讨论】:

  • 我从其他应用程序中经常收到此错误,我的猜测是 1. 当我们尝试引用它时,窗口有时还没有准备好,并不理想,但可以通过延迟。 2. 窗口发生变化,例如在 Safari 中,当我在点击 url 后立即引用窗口时以及页面完全加载后出现错误。当我运行命令时,终端也会发生。
  • 除非您打算在代码的其他部分或与其他 script objects 等一起使用声明为 Global 的变量,否则……global frontApp, frontAppName, windowTitle 不是必需的,可以删除。跨度>

标签: macos window applescript


【解决方案1】:

以下repeat loop 添加到您的 AppleScript 代码应该可以解决问题

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    tell process frontAppName
        repeat until exists of ¬
            (1st window whose value of attribute "AXMain" is true)
            delay 0.1
        end repeat
        tell (1st window whose value of attribute "AXMain" is true)
            set windowTitle to value of attribute "AXTitle"
        end tell
    end tell
end tell

return {frontAppName, windowTitle}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 2016-01-29
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    相关资源
    最近更新 更多