Open URL in new Safari tab with AppleScript

Is it possible to use AppleScript to open a link in a new tab in Safari?


Solution 1:

This will work:

tell application "Safari"
    tell window 1
        set current tab to (make new tab with properties {URL:"http://www.stackoverflow.com"})
    end tell
end tell

Solution 2:

I think this also does what you asked for, but it is much shorter and is less browser-specific:

do shell script "open http://www.webpagehere.com"

This will open the specified URL in your default browser. And if you explicitly want to open it in Safari, use this:

do shell script "open -a Safari 'http://www.webpagehere.com'"

Solution 3:

This should usually create a new tab and focus it (or focus an existing tab if the URL is already open):

tell application "Safari"
    open location "http://stackoverflow.com"
    activate
end tell

It opens a new window if "Open pages in tabs instead of windows" is set to never though.

tell application "System Events" to open location doesn't work with some URLs that contain non-ASCII characters:

set u to "http://ja.wikipedia.org/wiki/漢字"
tell application "System Events" to open location u
--tell application "Safari" to open location u
--do shell script "open " & quoted form of u

This opens a new tab even when new pages are set to open in windows:

tell application "Safari"
    activate
    reopen
    tell (window 1 where (its document is not missing value))
        if name of its document is not "Untitled" then set current tab to (make new tab)
        set index to 1
    end tell
    set URL of document 1 to "http://stackoverflow.com"
end tell
tell application "System Events" to tell process "Safari"
    perform action "AXRaise" of window 1
end tell

set index to 1 doesn't raise the window, but it makes the window appear as window 1 to System Events, which can AXRaise it.