Alex Gurr
Alex Gurr

Reputation: 543

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

Script:

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}

It works some times, but other times I get things like: [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)

Any ideas?

Thanks!

Upvotes: 0

Views: 2288

Answers (1)

wch1zpink
wch1zpink

Reputation: 3142

This following repeat loop added to your AppleScript code should do the trick

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}

Upvotes: 2

Related Questions