如何用Safari脚本在Safari中打开一个新窗口和多个URL?

sev*_*ens 6 safari macos applescript

如何在safari中打开一个新窗口,然后使用苹果脚本在该窗口中打开包含不同URL的多个选项卡?

Ant*_*sky 9

在Safari中创建新窗口的方法是使用以下make new document命令:

make new document at end of documents with properties {URL:the_url}
Run Code Online (Sandbox Code Playgroud)

这将创建一个新窗口,其中单个选项卡指向the_url并使该窗口位于最前面.请注意,make new window at end of windows这不起作用,只是"AppleEvent处理程序失败"错误.

同样,要在窗口中创建新选项卡w,您可以使用make new tab:

make new tab at end of tabs of w with properties {URL:the_url}
Run Code Online (Sandbox Code Playgroud)

这将在选项卡w列表末尾的窗口中创建一个新选项卡; 此选项卡将指向the_url,它不会是当前选项卡.tabs of w您也可以使用tell w块来代替明确说明:

tell w
    make new tab at end of tabs with properties {URL:the_url}
end tell
Run Code Online (Sandbox Code Playgroud)

那样,tabs含蓄地指tabs of w.

把这一切放在一起,我们得到以下脚本.给定一个URL列表the_urls,它将在一个新窗口中打开所有URL ; 如果the_urls为空,则打开一个带有空白选项卡的窗口.

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
Run Code Online (Sandbox Code Playgroud)