Applescript to split Safari tabs into new window
Asked Answered
C

2

5

I'm trying to write a script that splits the current + all next tabs into a new window — which would be super useful for organization.

It is perfectly possible to get the URLs of the current and all next tabs, make a new window and load all those URLs in new tabs, and then close the tabs in the original window – but that seems very cumbersome and slow.

So, is there any way to move a set of Safari tabs to a new window without actually reloading the URLs?

Cence answered 6/1, 2019 at 21:27 Comment(1)
You can move tabs with the move command, for example move tabs 2 thru 5 of window 1 to window 2.Latham
C
7

Not sure if this is the best/right way, but got this working:

tell application "Safari"
    set original_window to front window
    set tab_index to index of current tab of original_window
    set tab_limit to index of last tab of original_window

    make new document
    move tabs tab_index thru tab_limit of original_window to front window
    close first tab of front window
end tell
Cence answered 8/1, 2019 at 10:29 Comment(5)
You do not need set tab_limit to index of last tab of original_window, use -1 for the last tab, e.g.: move tabs tab_index thru -1 of original_window to front windowNutritious
Also, this doesn't work with private browsing (it will split tabs from a private window into a regular window). Still figuring that out.Cence
If the original window is using private browsing then instead of make new document use tell application "System Events" to keystroke "n" using {shift down, command down} to open a new private browsing window.Nutritious
Yeah, I've got that part already, but detecting if we're in private browsing isn't that simple. There was a trick but it supposedly no longer works.Cence
This script does work in Safari 15.5 on Monterey as written in this answer, but the suggestion in comment 1 from @Nutritious does not. It also will split tabs from a tab group into a new window, but I've not been able to figure out how to split a tab group into another tab group.Concelebrate
A
0

Here’s a slightly modified version that accounts for pinned tabs, rather than always closing the first tab in the new window:

tell application "Safari"
    set original_window to front window
    set current_tab_index to index of current tab of original_window
    set last_tab_index to index of last tab of original_window
    
    make new document
    # Account for pinned tabs; if we assume index 1, we'll close a pinned tab:
    set new_blank_tab to index of last tab of front window
    move tabs current_tab_index thru last_tab_index of original_window to front window
    close tab new_blank_tab of front window
end tell
Anthony answered 1/3, 2024 at 19:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.