How to focus tabs in Safari with AppleScript and avoid opening new ones

tell application "System Events"

activate application "Safari"

key code 19 using command down -- cmd 2 open a second tab or activate it if open

open location "http://example.com"

end tell


This works fine as long as one of these are true

1. the 2nd tab does not yet exist in which case it will make the 2nd tab and open the url in that location. Or..

2 If the 2nd tab already exists, it will activate the 2nd tab and reload the page as long as the 2nd tab is already at the website location we want it to be.


But if you have say 2nd or more tabs open and you run this, if the 2nd tab isd not already on the url you want it to be it will activate the 2nd tab and then open the website location in a new tab.


What I would like it to do is something like

key code 19 using command down

set location of current tab of window 1 in application safari to "http://example.com"


But this obviously doesn't work. So how can I tell Safari to only use the tabs I specify instead of opening new ones every time?

iMac, OS X El Capitan (10.11.3)

Posted on May 22, 2016 2:13 AM

Reply
2 replies

May 22, 2016 6:51 AM in response to Crackbot

Hi,


To set the focus to some tab: use the "current tab" property of the window.

To open a URL: use the URL property of the tab instead of the "open location"command.


Like this script:

-------

set theUrl to "http://example.com"

tell application "Safari"

if not (exists current tab of front window) then make new document -- if no window

tell front window

if (counttabs) = 1 then -- open the URL into the new tab

set current tab to (make new tab at end of tabs with properties {URL:theUrl})

else -- 2 or more tabs

set current tab to tab 2 -- focus the second tab

set URL of current tab to theUrl -- change the URL of the second tab

end if

end tell

end tell

-------

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to focus tabs in Safari with AppleScript and avoid opening new ones

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.