An AppleScript for Safari: Split Tabs to New Window

I finally got around to scratching a longstanding itch. I’m an inveterate web browser tab hoarder, and a scenario I frequently encounter is wanting to move the most recent (typically, rightmost) tabs into a new window all by themselves. Let’s say, for example, I have 26 tabs open in the frontmost Safari window, A through Z. The current selected tab is X. This script will move tabs X, Y, and Z to a new window, leaving tabs A through W open in the old window. It starts with the current tab, and moves that tab and those to the right.

I have the script saved in my FastScripts scripts folder for Safari, but I tend to invoke it from LaunchBar (which I have configured to index my entire scripts folder hierarchy). Command-Space to bring up LaunchBar, type “spl” to select this script, hit Return, done.

Worth a warning though: “moving” tabs with this script doesn’t actually move them like drag-and-drop does. The tabs “moved” by this script will reload in the new window, so you’ll lose (a) the current scroll position, and, more dangerously, (b) any text you’ve entered in a text field in the web page.

I have no idea how many others might want this, but in recent years here at DF I’ve gotten away from sharing my occasional scripting hacks, and feel like I ought to get back to sharing them. Can’t let Dr. Drang have all the fun.

Update: Leon Cowle adapted my script to be more elegant and concise. If you’re using this but grabbed the script before 10:30pm ET, go back and re-grab it.

Second update, 1 March 2024: Via this Stack Overflow thread, the script now uses a remarkably elegant solution that’s effectively just 7 lines of code, with no loops.

Tuesday, 5 December 2023