tags:

views:

32

answers:

2

After running some of my script, I happen to have a bunch of Safari window that has the "Untitled" windows.

I came up with the following code to close all the windows that have "Unitlted" as name, but it doesn't close everything with an error message -> "Safari got an error: Can’t get item 9 of every window. Invalid index." I had to run multiple times to close all the windows.

tell application "Safari"
    repeat with w in windows
        if name of w is "Untitled" then
            tell w to close
        end if
    end repeat
end tell

What might be wrong?

+1  A: 

The problem is that when you close a window, the number of windows changes and your loop breaks because eventually one of the windows that you started looping over isn't there anymore (because you're modifying the loop variable in the middle of the loop).

If you turn on the Events and Replies logs, you can see what's happening a little more clearly.

Here's a try at a fix. This loops as many times as there are windows. If window #1 is untitled, it is closed. If not, then we proceed with window #2, and on.

tell application "Safari"
    set windowNumber to 1
    repeat the number of windows times
        if name of window windowNumber starts with "Untitled" then
            close window windowNumber
        else
            set windowNumber to windowNumber + 1
        end if      
    end repeat
end tell

My applescript is really rusty. I'm certain there is a simpler way to do it (i.e., some kind of close all windows whos name starts with "Untitled" syntax), but this seems to work.

Seth
+3  A: 

Use an AppleScript filter reference form:

tell application "Safari"
    close (every window whose name is "Untitled")
end tell
sakra