Getting URLs For Tabs From Safari

I have recently had a need to share the links to a bunch of tabs. While I could’ve just gone through each one and copied them individually (the clipboard merging feature in Alfred makes this fairly trivial), that sounds like an unnecessarily large amount of effort. So I wrote an AppleScript to do it instead.

Since I had all the tabs I wanted isolated to a single window, I first started with a script that only gets the URLs from the tabs in the current (frontmost) window.

tell application "Safari"
    set output to ""
    repeat with t in tabs in first item in windows
        set output to output & the URL of t & "\n"
    end repeat
    return output
end tell

While this was sufficient for me, I also modified it to support getting the URLs of all tabs across all windows. Here, I filter on closable windows, as there can be non-closable ones that don’t have tabs and fatal (I think it’s the Downloads window, but am not sure).

tell application "Safari"
    set output to ""
    repeat with w in every window
        set c to closeable of w
        if (c = true) then
            repeat with t in every tab of w
                set output to output & the URL of t & "\n"
            end repeat
        end if
    end repeat
    return output
end tell

Running AppleScripts

The easiest way to run these is to copy the one you want, open the AppleScript Editor (in /Applications/Utilities/), create a new file, paste and then hit Run (cmd-R). You should then end up with something like this (I ran the second script):

Alternatively, you can run it from the command line (over SSH or just via Terminal). Simply copy, start typing osascript <<<' (the opening quote is important), paste, add in the closing quote and hit enter. You’ll get the same output, just on the command line. If you’re working locally, you can just copy then run pbpaste | osascript instead.

PayPal: simon@simon.geek.nz

 

Leave a Reply