AppleScript Safari URL tip: How to open multiple URLs in Safari tabs

Well, I set out to write a simple tip on how to activate a Mac application using AppleScript, and I ended up writing a program to open a list of URLs in separate tabs in Safari using AppleScript. (Yeesh, I really took a detour. Oh, well.)

Without any further ado, here's the source code for this AppleScript program:

-- an applescript program that opens a list of urls in separate tabs.
-- opens safari, then loads each url in a separate tab.
-- written by alvin alexander, devdaily.com
-- no rights reserved, feel free to copy and improve this program.

set urlList to {"http://www.macintouch.com/", "http://www.macnn.com/", "http://www.macworld.com/", "http://www.thinksecret.com/", "http://www.tuaw.com/"}
set numURLs to (count urlList)

tell application "Safari"
  activate
  -- create all the tabs that are needed
  tell application "System Events"
    -- enter the url in the open window
    keystroke (item 1 of urlList)
    key code 36
    repeat with i from 2 to (numURLs)
      -- for each additional url, first create a tab
      tell process "Safari"
        click menu item "New Tab" of menu "File" of menu bar 1
      end tell
      -- now enter the url
      keystroke (item i of urlList)
      key code 36
    end repeat
  end tell
end tell

Brief description of the code

Here's a brief description of what this AppleScript program does:

  • urlList is a simple list with the URLs I want Safari to open.
  • The repeat statement starts the loop.
  • I'm clicking File :: New Tab using the System Events because I can't figure out how to get this to work by calling Safari directly. (I'm currently using Safari 3.0.3.)
  • The keystroke command types the URL into Safari.
  • key code 36 is needed to hit the [Enter] key.

Again, I had to take a few extra steps here because I couldn't script the tabs in Safari directly. Ideally code like this would have worked inside the tell application "Safari" statement:

tell window 1
 make new tab
end tell

Hopefully that support will be available in the future, or, if I'm mistaken, please send me an email and I will correct this program.