Search code examples
macosscriptingwindowapplescript

How do I bring a Safari window to the foreground using a window ID in AppleScript?


I have a script that, among other things, records the browser window it was activated on when it was launched. Things happen in the middle, and then the script needs to go back to the original window and tab it was called on.

Problem is, a user may change the active window or tab during the script's run. I want to return to the window and tab that was used when the script was called.

Here's how I'm trying (and failing) to do this:

tell application "Safari"
    if (id of front window) is not (windowID of browserInfo)
        display dialog "Made it in the block!"
        display dialog (get index of window 1)
        display dialog (get index of window (windowID of browserInfo))
-- ...

The dialogs are all for debugging, of course. Now, browserInfo is an object whose windowID property corresponds to the Safari window where the script was called. This is usually something like '889' or '1195' or some other number.

Now, what's interesting is the first four lines fire properly when simulating a user that started in one window, then activated another. The fourth line returns '1', as expected. But the fifth line gives an error: Safari got an error: Can't get window 809. Invalid index.

How can I get the index of a Safari window when all I can use is an ID?

(And yes, URL and window title are fine things, but they are out of bounds for my application. Users may have multiple windows open with the same URL and window title. So I need the specific window ID.)


Solution

  • I believe this is what you're after...

    on run
        tell application "Safari"
            set myID to id of window 1
            set myTab to current tab of window 1
        end tell
    
        do shell script "sleep 8" -- simulates time where user may change tabs
    
        tell application "Safari"
            set index of window id myID to 1
            set current tab of window 1 to myTab
        end tell
    end run