Search code examples
macosapplescript

MacOSX: get foremost window title


I am using this code to get the window title:

tell application "System Events"
    set frontApp to name of first application process whose frontmost is true
end tell

tell application frontApp
    set window_name to name of front window
end tell

However, this fails in some cases. Obviously it fails when there is no open window but that is Ok. However, in some cases, for example for Texmaker, it fails with an error. It also doesn't work for Preview.

What would be a way to get the window title anyway, even for cases like Texmaker?


Solution

  • This seems to work always:

    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}
    

    Got the idea from Getting the currently open file and path from Preview.