通过 Applescript 激活 Window 会引发错误,"Can’t get window 1 of process"

Getting Active Window via Applescript throws error, "Can’t get window 1 of process"

脚本:

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)

有什么想法吗?

谢谢!

将以下 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}