Personal tools
You are here: Home Weblog Closing Tabs in Safari with AppleScript

Closing Tabs in Safari with AppleScript

Posted by Sean Fulmer at Apr 10, 2008 11:03 PM |

More adventures in browser tab manipulation

A lot of stuff has happened in the past couple of months, mostly because of the fact that I got a new job. This is the first time in the last three years that I've had a steady income - and it feels great. I had no idea how much stress I was putting on myself as a freelancer!

Anyway - the point: steady income => more money => shiny new iMac => I'm no longer using Epiphany as my main browser, so I needed to cook up a way to quickly close a bunch of tabs in Safari. Safari already has a way to close all tabs except the current tab, so we just need a way to close tabs to the left or to the right of the current tab. AppleScript to the rescue!

First, the left tabs:

tell application "Safari"
    set cWindow to first item of windows
    set ctIndex to index of current tab of cWindow
    repeat ctIndex - 1 times
            close first item of tabs of cWindow
    end repeat
end tell
open location "x-launchbar:hide"

Then, the right:

tell application "Safari"
    set cWindow to first item of windows
    set ctIndex to index of current tab of cWindow
    repeat while (count of tabs of cWindow) > ctIndex
            close last item of tabs of cWindow
    end repeat
end tell
open location "x-launchbar:hide"

I save those as "Close Left Tabs" and "Close Right Tabs" in ~/Library/Scripts. When I need to use them, I just bang a couple of keys to bring up the very-excellent LaunchBar [1], then 'CL' or 'CR' to run whichever one I need.

So, this is great for me and Safari, but it doesn't bode well for the similar work I did for Epiphany. There's a problem with that one, I think related to the disconnecting of GTK signals. The symptom is that if you're using that extension, Epiphany won't cleanly exit after you've closed all of its windows. And the real problem is that since I'm not in GNOME most of the time these days, I'm really not feeling an urgent need to fix it, which sort of sucks if you happen to be using this extension with Epiphany.

So, if you're one of those two people... feel free to hack on it ;)

[1]Hence the "x-launchbar:hide" bit at the end of each script - feel free to omit those :)
Document Actions