djbritt
djbritt

Reputation: 77

AppleScript: Toggle Between Safari Windows?

If I have two safari windows open, just one tab in each, how do I get applescript to switch to either of the windows at will? Or in other words, toggle between them.

I tried, activate window 1 (or, the first window), and activate window 2 (or the second window), only ever activates the first window.

I tried open window 1 etc, open doesn't exist.

I tried using the system events, click menu bar 1 option, thinking maybe menu bar 2 was for window 2, didn't work.

I tried making do javascript on a specific tab show that page, couldn't get that to work.

Ultimately I did figure out I could use a keyboard shortcut, but I wanted to see if there was a more 'vanilla' applescript way.

Upvotes: 0

Views: 368

Answers (2)

djbritt
djbritt

Reputation: 77

When I do just this

tell application "Safari"
  set index of window 2 to 1
end tell

The new window that shows up is frozen. I fixed this by doing this

    tell application "Safari"
    set theWindows to windows
    set win2 to item 2 of theWindows
    tell win2
        set visible to false
        set visible to true
        set index to 1
    end tell
    activate
end tell

Upvotes: -1

vadian
vadian

Reputation: 285059

  • If the windows are not full screen (in different spaces) just change the index of the window

      tell application "Safari"
          set index of window 2 to 1
      end tell
    
  • If the windows are in different spaces you have to switch the spaces by executing the keystrokes with System Events. The default values on the US keyboard are ⌃←

      tell application "System Events"
          key code 123 using (control down)
      end tell
    

    and ⌃→

      tell application "System Events"
          key code 124 using (control down)
      end tell
    

Upvotes: 0

Related Questions