Applescript - Bring window to foreground

37,012

Solution 1

If your application is scriptable and allows setting the index of a window, you can do the following (based on an answer in How do I make a Safari window active using AppleScript (elegantly)?)

to raiseWindow of theApplicationName for theName
    tell the application named theApplicationName
        activate
    set theWindow to the first item of ¬
        (get the windows whose name is theName)
    if index of theWindow is not 1 then
            set index to 1
            set visible to false
            set visible to true
        end if
    end tell
end raiseWindow

The toggling of the visibility is necessary to deal with some weirdness that occurs with switching applications. If you don't toggle the visibility, the window won't be the first when you switch away from and back to the application. Unfortunately, this toggling shrinks the window to the dock then restores it, a very dramatic UI disruption.

Here's another way I've found to deal with the weirdness:

to raiseWindow2 of theApplicationName for theName
    tell the application named theApplicationName
        activate
    set theWindow to the first item of ¬
        (get the windows whose name is theName)
        if the index of theWindow is not 1 then
            set the index of theWindow to 2
        tell application "System Events" to ¬
            tell application process theApplicationName to ¬
                keystroke "`" using command down
        end if
    end tell
end raiseWindow2

Solution 2

This is possible by using the "AXRaise" action, except on certain window (applications that use X11 for example).

Try this.

set theTitle to "some title"
tell application "System Events"
    tell process "appIT"
        set frontmost to true
        perform action "AXRaise" of (windows whose title is theTitle)
    end tell
end tell
Share:
37,012

Related videos on Youtube

Giorgio
Author by

Giorgio

Updated on July 22, 2022

Comments

  • Giorgio
    Giorgio 2 months

    I have an application with several windows opened at the same time. I'd like to bring a specific window to foreground (I know its title).

    At the moment I'm using a combination of keys to achieve this task but I'd like to try something different since I'm experiencing some problems with this approach.

    tell application "System Events"
        set frontmost of process "appIT" to true
        keystroke "1" using command down
        delay 0.2
    end tell
    
  • Anton Koval'
    Anton Koval' over 6 years
    On OS X Yosemite, execution of this script gave me error (can not just copy-paste because I have localized error message): System Events got error: Unable to configure process "appIT" to true. Something had changed since 2012?
  • ling
    ling almost 6 years
    @AntonKoval' perform action "AXRaise" of window 1 works for me in yosemite
  • LiMar
    LiMar over 1 year
    Works on Catalina. Should be the accepted answer.

Related