AppleScript Programming/Sample Programs/Safari Quit Warning

Note: This script is obsolete for its purpose, since by these days Safari prompts user for confirmation if there is more than one window/tab open while quitting. But as the code itself is valid, it may be kept as a general example.

This is quite much doing same than Firefox's alert box that pops up when you're about to quit the browser with more than one window/tab open.

I use external tool (iKey) to force this script to be run when cmd+Q is hit while Safari is active application. I just plain hate it, when I mispress it instead of cmd+W or opt+Q.

(*
I made the code ignore window "Downloads", as it is relatively
irrelevant, especially since Safari already alerts if you got downloads
going. Plus, if you once open that window, Safari will count it open
even when you close it - until you quit Safari.

If you don't use English as OS language, then change it to represent
the window name in the language you use - in variable setting just
right after this note ends - if you want to (not necessary if you
don't care what counts the alert gives).

Enjoy your browsing. :)

F-3000
*)

set wDowns to "Downloads"

tell application "Safari"
	set wCounter to 0 -- Window Counter
	set bCounter to 0 -- Button Counter
	set wList to name of every window
	repeat with vWindow in wList
		-- Counts the amount of windows
		set wCounter to wCounter + 1
		(* Counts the amount of tabs.
		I did put it into try-block so that "Downloads"-window wont 
		mess this script up, since it doesn't have "group 3"-item.
		Luckily - regarding easiness of tab-counting. *)
		try
			tell application "System Events" to tell process "Safari" to set bCounter to ¬
				bCounter + (count (every button in group 3 of window vWindow))
		end try
	end repeat
	-- Causes  "Downloads"-window to be ignored in counting
	if wList contains wDowns then set wCounter to wCounter - 1
	if wCounter > 0 then
		-- If there is more than 1 window open...
		display dialog "Do you really want to quit Safari?" & ¬
			return & "You have " & wCounter & " windows and " & bCounter & " tabs open." buttons ¬
			{"Yes yes yes!", "No, forget it"} default button 2 with icon stop with title "Oops!"
		if button returned of result is "Yes yes yes!" then quit
	else
		-- If no windows are open...
		quit
	end if
end tell
Next Page: MS Word 2008 | Previous Page: Calculator
Home: AppleScript Programming/Sample Programs