Restart Safari restoring windows and tabs

Alec Jacobson

August 13, 2009

weblog/

Safari only resets its JRE cache at restart. So when I am developing Java applets and testing them in my Safari browser, I have to restart Safari every time I recompile to view my changes. I have tried deleting the JRE cache manually and using Safari > Empty Cache, but the JRE cache is still there. Only restarting has worked. So the least I could do is write an applescript to restart Safari and restore any windows and tabs I might have had open. Here's my script:
-- Get all windows and their tabs as nested list
set url_list to {}
tell application "Safari"
	activate
	set tab_list to {}
	repeat while (count of documents) > 0
		set doc_count to count of documents
		set this_doc to front window
		set tab_list to tab_list & URL of front document of this_doc
		tell application "System Events" to keystroke "w" using {command down}
		if doc_count is not equal to (count of documents) then
			set url_list to url_list & {tab_list}
			set tab_list to {}
		end if
	end repeat
end tell

-- Save list to preference files just in case
-- convert url list  to text
set old_delim to AppleScript's text item delimiters
set url_text to ""
set AppleScript's text item delimiters to " "
repeat with this_item in url_list
	set url_text to (url_text & this_item as text) & return
end repeat
set AppleScript's text item delimiters to old_delim

-- get path to prefs file where URLs will be stored
set prefs_folder to path to preferences folder as string
set prefs_file to prefs_folder & "Safari Saved URLs"

try
	set open_file to ¬
		open for access file prefs_file with write permission
	-- erase current contents of file:
	set eof of open_file to 0
	write url_text to open_file starting at eof
	close access open_file
on error
	try
		close access file prefs_file
	end try
end try
display dialog url_text

-- Restart Safari
tell application "Safari" to quit
repeat while appIsRunning("Safari")
	delay 1
end repeat
tell application "Safari" to activate

-- Restore windows and tabs
tell application "Safari"
	repeat with i from 1 to length of url_list
		set this_doc to front document
		if i is not equal to 1 then
			set this_doc to make new document at end of documents
		end if
		repeat with j from 1 to length of (item i of url_list)
			set URL of this_doc to item j of (item i of url_list)
			if j is not equal to length of (item i of url_list) then
				tell application "System Events" to keystroke "t" using {command down}
			end if
		end repeat
	end repeat
end tell

-- http://codesnippets.joyent.com/posts/show/1124
on appIsRunning(appName)
	tell application "System Events" to (name of processes) contains appName
end appIsRunning
Note: I save the list of window and tab URLs as text in ~/Library/Preferences/Safari Saved URLs. That way if something goes wrong I have a second chance at retrieving the URLs I had open. Perhaps this is entirely unnecessary.