Skip to content

Instantly share code, notes, and snippets.

@ChristoferK
Created June 17, 2018 02:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristoferK/5f41f9b11de9d07119068a0238ce36cd to your computer and use it in GitHub Desktop.
Save ChristoferK/5f41f9b11de9d07119068a0238ce36cd to your computer and use it in GitHub Desktop.
[Open URLs in Safari] An AppleScript that receives a list of URLs as input and opens them in new tabs of a specified existing window or, optionally, a new window, and can be set to do this in the background or by raising Safari to the foreground #Safari #tabs #URLs #AppleScript
property S : a reference to application "Safari"
global W
on run input -- input is a list of URLs
if (count input) is 0 then ¬
set the input to {¬
"alfredapp.com", ¬
"stackoverflow", ¬
"google.co.uk"}
-- List all currently open window id's in numerical order
if S is not running then
set W to {}
else
set my text item delimiters to linefeed
set W to the id of every window of S
do shell script "sort -n <<<" & quoted form of (W as text)
set W to the paragraphs of the result
end if
repeat with |URL| in the input
set |URL| to the contents of the |URL|
openURLinSafari to |URL| at end of W without focus
end repeat
end run
to openURLinSafari at wID as integer : 0 to www ¬
given focus:focus as boolean : false
local www, wID, focus
-- Check the supplied URL has a scheme component (http://, ftp://, etc.)
if www does not contain "://" then set www to ["https://", www] as text
-- Check for absence of tLD and append .com if needed
if www does not contain "." then set www to [www, ".com"] as text
tell application "Safari"
if wID is 0 then -- Make new window
make new document with properties {URL:www}
-- Get the id of the newly-opened window
get the first window whose id > (end of W as integer)
set wID to the result's id
set the end of W to wID as text
set T to current tab of window id wID
else -- Make new tab
tell window id wID to set T to make new tab ¬
with properties {URL:www}
end if
-- Bring the window and tab into focus
if focus then
set the index of window id wID to 1
set the current tab of window id wID to T
activate
end if
end tell
end openURLinSafari
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment