How do you open a new window in safari and then open multiple tabs with different urls in that window using apple script?
The way to create a new window in Safari is to use the make new document
command:
make new document at end of documents with properties {URL:the_url}
This will create a new window with a single tab pointing to the_url
and make that window frontmost. Note that make new window at end of windows
doesn't work, and just errors out with "AppleEvent handler fails".
Similarly, to create a new tab within a window w
, you can use make new tab
:
make new tab at end of tabs of w with properties {URL:the_url}
This will create a new tab in window w
at the end of the list of tabs; this tab will be pointing to the_url
, and it won't be the current tab. Instead of explicitly saying tabs of w
, you can also use a tell w
block:
tell w
make new tab at end of tabs with properties {URL:the_url}
end tell
That way, tabs
implicitly refers to tabs of w
.
Putting this all together, we get the following script. Given a list of URLs in the_urls
, it will open all of them in a new window; if the_urls
is empty, it opens a window with a blank tab.
property the_urls : {¬
"http://stackoverflow.com", ¬
"http://tex.stackexchange.com", ¬
"http://apple.stackexchange.com"}
tell application "Safari"
if the_urls = {} then
-- If you don't want to open a new window for an empty list, replace the
-- following line with just "return"
set {first_url, rest_urls} to {"", {}}
else
-- `item 1 of ...` gets the first item of a list, `rest of ...` gets
-- everything after the first item of a list. We treat the two
-- differently because the first item must be placed in a new window, but
-- everything else must be placed in a new tab.
set {first_url, rest_urls} to {item 1 of the_urls, rest of the_urls}
end if
make new document at end of documents with properties {URL:first_url}
tell window 1
repeat with the_url in rest_urls
make new tab at end of tabs with properties {URL:the_url}
end repeat
end tell
end tell
tell application "Safari"
activate
set the URL of document 1 to "http://www.XXXXXXX.com"
my new_tab()
set the URL of document 1 to "http://www.XXXXXX.com"
end tell
on new_tab()
tell application "Safari" to activate
tell application "System Events"
tell process "Safari"
«event prcsclic» «class menI» "New Tab" of «class menE» "File" of «class mbar» 1
end tell
end tell
end new_tab
Replace the X's with whatever sites you want and keep repeating the code (my new_tab() and set the URL... lines) for each page you'd like to have open. Referring to this page. Correct me if this isn't what you were talking about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With