Choose Safari Tab

Hey Folks,

I finally got annoyed enough to update my Choose Safari Tab script to handle duplicate tab names.

The script produces a choose from list to pick the tab you want to bring forward. It displays the number of open document-windows and tabs, and it shows which is the current tab in each window.

Tabs are segregated by window and listed in index order.

Pure vanilla; very fast.


------------------------------------------------------------------------------------------
# Auth: Christopher Stone <junksieve@thestoneforge.com>>
# dCre: 2010-10-16 : 00:42
# dMod: 2013-05-30 : 18:25
# Appl: Safari
# Task: Display a list of tab names and also a count of both documents & tabs.
#       : Select a tab name to bring it to the front.
#       : Adjusted to deal properly with duplicate tab names on 2013-05-30.
# Libs: Only stock OSX components used.
# Osax: None 
# Tags: @Applescript, @Safari, @Choose, @Display, @Tabs, @Windows
-------------------------------------------------------------------------------------------
try
	
	set sep to "----------------------------------------------------------------------------------------------------"
	
	tell application "Safari"
		
		if (count of document) ≥ 1 then
			set frontWindoc to document of front window
		else
			error "No pages are open in Safari"
		end if
		
		tell (every window where its document is not missing value)
			set docCount to count
			set currentTabIndex to index of current tab
			set tabCount to count of tabs
			set tabNames to name of tabs
		end tell
		
		if docCount < 10 then set docCount to "0" & docCount
		set hdrText to "Window Count: " & docCount & return & "      Tab Count: " & tabCount
		
		# Add tab-index to tab names to deal with duplicate names.
		set ndx to 0
		repeat with i in tabNames
			repeat with n from 1 to (length of i)
				if n < 10 then
					set _num to "0" & n
				else
					set _num to n
				end if
				tell (a reference to item n of i) to set its contents to its contents & " ¡ [" & _num & "]"
			end repeat
		end repeat
		
		# Mark Current Tabs of each document window with '✓'
		# tabNames is a list of lists.
		set ndx to 0
		repeat with i in tabNames
			set ndx to ndx + 1
			tell (a reference to i's item (item ndx of currentTabIndex)) to set its contents to (its contents) & " ✓"
			if ndx = 1 then
				set currentTabName to result
			end if
			set end of i to sep
		end repeat

		set beginning of item 1 of tabNames to sep
		set AppleScript's text item delimiters to return
		set tabNames to paragraphs of (tabNames as text)
		
		set _tab to choose from list tabNames with title "¢¢ Safari Tab Names ¢¢" with prompt hdrText 
			default items {currentTabName} with empty selection allowed
		
		if _tab = false then return
		
		set _tab to item 1 of _tab # De-listify.
		set AppleScript's text item delimiters to " ¡ "
		set tabName to text item 1 of _tab
		set AppleScript's text item delimiters to {"[", "]"}
		set tabIndex to (text item 2 of _tab) as integer
		
		tell windows
			set tabID to tabs whose name contains tabName and index is tabIndex
		end tell
		
		repeat with i in tabID
			try
				set tabID to item 1 of i
				exit repeat
			end try
		end repeat
		
		try
			tabID as number
		on error eStr
			set AppleScript's text item delimiters to " of "
			repeat with i in (text items of eStr)
				if i contains "window id" then
					set winOfTabID to run script ((contents of i) & " of application \"Safari\"")
					exit repeat
				end if
			end repeat
		end try
		
		set winOfTabIdDoc to winOfTabID's document
		if current tab of winOfTabID ≠ tabID then set current tab of winOfTabID to tabID
		
		if winOfTabIdDoc ≠ frontWindoc then
			set newDoc to make new document
			set index of winOfTabID to 1
			close newDoc
		end if
		
	end tell
	
on error e number n
	set e to e & return & return & "Num: " & n
	tell me to set dDlg to display dialog e with title "ERROR!" buttons {"Cancel", "Copy", "OK"} default button "OK"
	if button returned of dDlg = "Copy" then set the clipboard to e
end try
-------------------------------------------------------------------------------------------

1 Like

Hello.

That’s a nice one!

What do you think about this? It searches tabs titles and url’s by regexp, but it will only return the first tab with that particular url, on the other hand, it tries to detect if the page is in another space.

It also has a “all” option for displaying all tabs, but doesn’t show which window it belongs to.

P.S It is faster than the length of it should indicate. :wink:
D.S

They’re both very stylish from the user-experience perspective! :slight_smile:

One problem with McUsrII’s use of an invisible application to display the dialog is that, if the dialog gets covered over before it’s dismissed ” say you’ve decided to look at something else first ” you have to keep quitting or hiding apps to get at it again. And in the case of SystemUIServer, you can’t use most of the items on the right of the menu bar until you do!

It looks good and is fast enough to not notice any delay when run from FastScripts on my machine.

You’re using -u on the sort to produce unique names, but duplicate tab names do not necessarily equate with duplicate tabs. For instance here on MacScripter you can have ‘MacScripter / Search Results’ pages with different content.

For that matter I want to know when I have duplicate tabs, so I can close them. I still only have 4GB of memory on my MacBook Pro, and Safari is greedier than ever these days.

All is ‘.*’ ?

[ Edit: I didn’t notice the “All” button. I just naturally input a regex. :slight_smile: ]

It seems to me that the search string should be faithfully reproduced even if it’s “All”, because if I searched for all once there’s a good chance I’ll want to do so again. (If I have 20+ tabs open for several days there’s a good chance I won’t remember what to search for. :slight_smile:

I haven’t figured out a way other than using tab index numbers to discriminate between duplicate names. Choose-from just doesn’t return enough info about what is returned, so you have no choice but to embed information in the list.

At this time I haven’t accounted for the possibility that two tabs with the same name could exist in two different windows and have the same index. I think this an unlikely occurrence and don’t want to fool with it at present.

Hello

I deliberatly let all, not be saved as a regexp, since you have a button for it, so that you sort of remember two searches. :slight_smile:

I really thought the displayed name of a tab is good enough, but maybe I ought to go back and check that up. And it has the fault of not playing well, if the download window is in front. But . if I am to make things 100% idiot proof, then I want money! :smiley:

Safari is a memory hog, and Flash must be something the Battery Producers have invented!

Hello.

I’d actually like to have duplicate tabs, should I need one in a different space. (That happens!).

But writing a script that sifts out duplicate url’s seems like a good idea to me. :slight_smile:

Even though I have 8GB mem, I run into the same problem with tabs and Safari, as I can end up with 250 open tabs at times. (Why do you think I wrote the script in the first place? :))

When I feel the machine start to heat up, then I run this:

tell application "Safari"
	set miniaturized of (every window whose miniaturized is false) to true
end tell

And then I open “uncollapse” the windows I need, a great thing with Safari, is that it seem to close the connections on minimized window, and the cpu-usage sinks instaneously.

I didn’t realize that and will scope it out. Good tip!

Well.

It seems to me that it uses the same amount of physical (wired) memory, but if you hit the info button, before and after you have collapsed the windows, in activity-monitor, you should notice, that that the list of open files and ports has become smaller. Also that the cpu-usage drops down, to below 20%, which at least I can live with (have 200%).

The effect I am after is reducing the heat, and that works!

It’s a bit awkward that I have to uncollapse, do a search, collapse again, and the uncollapsing the tab, (or windows that I want to read), but it is a circumvention, that works.

It is more awkward IMHO to have to find what you want in the log. By the way, I use Sessions, a plugin that keeps track of tabs and windows, that you can save and restore. Free, (and great!).

Hello.

And for the record, the first thing I do when I get a new Mac is to install pirated ram preferably from the ones that deliver to Apple. I see to that I have the correct screwdriver, and instructions up front.

Then I move to a room where there are no statical-electric discharges. I open the lid, on a tidy place, where I can put down the screws correctly. then I touch the screwdriver to the chaissis, to even out the capicity in me and my Mac. Then I take out the old, carefully, install the new, and starts using, the Mac hard during the weekend, having a burn-in party, where the fans really works. I use time on this, with good screw-drivers, as I really don’t want to leave a trace of what happened, for the hope, that it would pass as a guarrantee job the first year, should anything happen. I never buy AppleCare (Thouhg maybe I should, as it has helped friends of mine). You got to have a screwdriver with correct size.

If the ram hasn’t broken during the “burn-in” then, I guess it is ok, and I can start figuring out who wants to buy the old ram.

Pirated ram has never failed me, and I have saved like 50% on it every time!

Edit

I also touch the chasiss of the Mac with my fingers, after I have touched it with the screwdriver.

I do google some, before I settle on the brand for the ram, and the company to deliver it, terms, money-back guarrantee, etc.

It can also help to have a friend to install it. But your friend is not likely to as alert as you as to not leave any mark.

You should also check out how the insertion of a ram-chip works up front, you basically moves to levers aside and move it up some 30 degrees, and pulls it out, with your fingers, opposite way around when you put it in. And this is something that should be done, and studied with the most care. But instructions are available everywhere.

Edit++

And what may count for more than money, is that don’t have to send it away. :slight_smile:

This is a couple of script I have overhauled recently, so I can save flash-tabs, for later reopening, to save resources.

It saves Safari url’s to text file, and restores them later. First I thought of having the script close the window when it was done, but I figured it was best to leave it at the users discretion.

The first one saves them, you’ll have to adjust for the folder name as I have set up ~/Document/topics as the folder to save the files with the url’s in

tell application "Safari"
	set url_list to URL of every tab of its front window
	set aTabName to name of first tab of its front window
end tell

-- convert url_list to text
set old_delim to AppleScript's text item delimiters
set AppleScript's text item delimiters to return
set url_list to url_list as text
set AppleScript's text item delimiters to old_delim

set prefs_file to choose file name default name "topic.srfi" with prompt "Save the tabs of the window whose first tabname is \"" & aTabName & "\"" default location ((path to desktop folder as text) & "Topics") as alias
set itExists to true
try
	set prefs_file to prefs_file as alias
on error
	set itExists to false
end try

if itExists then
	appendToFile(url_list, prefs_file)
else
	writeFile(url_list, prefs_file)
end if

to writeFile(theData, theFile)
	(*For writing a file.  Handles situations where the new file may be
	 shorter than the original file, since AppleScript's write command doesn't 
	 reset EOF to the new data length.*)
	--returns boolean success (true=success)
	--Assumes: theFile is a file path string and file exists.	
	try
		-- open file
		open for access (theFile) with write permission
		copy the result to theFile_ID
		
		-- Set the file length to zero
		set eof theFile_ID to 0
		
		-- Write our message
		write theData to theFile_ID
		
		-- close the file
		close access theFile_ID
		return true
		
	on error
		try
			close access theFile_ID
		end try
		return false
	end try
end writeFile



to appendToFile(theData, theFile)
	(*For adding text to the end of a file*)
	--returns boolean success (true=success)
	--Assumes: theFile is a file path string and file exists.	
	try
		-- open the file
		open for access (theFile as alias) with write permission
		-- using "theFile as alias" means the file must already exist.
		-- if it doesn't then the attempt to append will fail
		copy the result to theFile_ID
		-- Get the file length
		get eof theFile_ID
		copy the result to theFile_eof
		
		-- Write our message
		write theData to theFile_ID starting at (theFile_eof + 1)
		
		-- Close the file
		close access theFile_ID
		return true
	on error
		try
			close access theFile_ID
		end try
		return false
	end try
	
end appendToFile


This one restores a window with the tabs, this works for me on Snow Leopard with Safari 5.1.7, but it isn’t perfect,
as the content pretty much controls, if they are going to open a new window, instead of getting into a tab and the like. (Some even opens up in the previous window.)

-- get path to prefs file where URLs are stored
set prefs_folder to path to preferences folder as string
set prefs_file to prefs_folder & "Safari Saved URLs"
set prefs_file to (choose file default location ((path to desktop folder as text) & "Topics") as alias) as text

try
	set open_file to ÂŹ
		open for access file prefs_file without write permission
	set url_list to read open_file using delimiter return
	close access open_file
	tell application "Safari"
		activate
		tell application id "com.apple.systemevents" to tell process "Safari" to keystroke "n" using command down
		tell tab 1 of window 1 to do JavaScript "self.focus()"
		set URL of tab 1 of window 1 to item 1 of the url_list
		set the url_list to the rest of the url_list
		repeat with the_url in url_list
			open location the_url
		end repeat
	end tell
on error
	try
		close access file prefs_file
	end try
end try

1 Like