How to close all safari documents except ones containing string match.

I am looking to get this script to loop through open Safari windows, and then close those windows containing a keyword in the url.

There is a problem if it finds a match but it is not the front window. If it deletes a window then it gets a count error at the end. - still a bit of a newbie.


tell application "Safari"
	activate
	repeat with x from 1 to (count documents)
		try
			if the URL of document x contains "mydomain.com" then
				beep
				tell application "System Events"
					tell process "Safari"
						click menu item "Close Window" of menu "File" of menu bar 1
					end tell
				end tell
			end if
			delay 1
		on error
			exit repeat
		end try
	end repeat
end tell

Hi,

try this


tell application "Safari" to close (documents whose URL contains "mydomain.com")

the error in your script occurs, because you count the documents at the beginning of the repeat loop
and then remove items from the list without changing the count variable.
For example, If there are 4 documents, the error occurs in the third iteration.
The script tries to remove document 3 but there are two documents left.

OMG one line - that is so cool :cool: