tell application "Safari"
repeat with theWindow in windows
if (name of theWindow as string) does not contain <subString> then -- where anything can be substituted to substring
close theWindow
end if
end repeat
end tell
I know one should not modify a list while parsing it, but is there something else?
It works on my machine just normal but I’m working with tabs as well in Safari and to close every tab/window I use something like this.
tell application "Safari"
set windowNames to name of every window
repeat with windowName in windowNames
tell window windowName
set tabNames to name of every tab
repeat with tabName in tabNames
if tabName does not contain "Apple" then
close tab tabName
end if
end repeat
end tell
end repeat
end tell
At the top of the repeat in your script, the repeat’s set up to work with the number of windows which are open at the time. However, it’s not working through a list of specific windows, but with the reference ‘windows’ ” that is, ‘every window of application “Safari”’. As the script closes the windows, Safari’s windows become fewer, but the repeat index keeps going up. Eventually the index becomes greater than the number of remaining windows and you get an error.
That’s the explanation! The cure is to get Safari to return a list of the windows first (where every item is a reference to a specific window) and to run the repeat against the list:
tell application "Safari"
set theWindows to windows -- Get a list of Safari's windows.
repeat with theWindow in theWindows
if (name of theWindow as string) does not contain "<subString>" then -- where anything can be substituted to substring
close theWindow
end if
end repeat
end tell
Or more simply:
tell application "Safari" to close (every window whose name does not contain "<subString>")
Thank you everybody, it was my mistake, indeed my script was working – but some pop-up windows seem to change their titles, making them difficult to close.