使用applescript关闭多个Safari窗口

时间:2010-08-21 02:03:13

标签: applescript

运行我的一些脚本之后,碰巧有一堆Safari窗口有“无标题”窗口。

我想出了以下代码来关闭所有以“Unitlted”作为名称的窗口,但它并没有关闭所有内容并显示错误消息 - > “Safari遇到错误:无法获取每个窗口的第9项。索引无效。”我必须多次运行才能关闭所有窗口。

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

可能出现什么问题?

3 个答案:

答案 0 :(得分:3)

使用AppleScript filter reference form

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

答案 1 :(得分:2)

问题是,当你关闭一个窗口时,窗口的数量会发生变化而你的循环会中断,因为最后你开始循环的一个窗口不再存在(因为你正在中间修改循环变量)的循环)。

如果启用“事件和回复”日志,您可以更清楚地看到发生的情况。

这是一个修复尝试。这循环次数与窗口一样多。如果窗口#1未命名,则关闭。如果没有,那么我们继续窗口#2,然后继续。

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

我的AppleScript 真的生锈了。我确信有一种更简单的方法(即某种close all windows whos name starts with "Untitled"语法),但这似乎有效。

答案 2 :(得分:0)

这对我有用:

tell application "Safari"
    close (every tab of every window whose name starts with "some_text")
end tell

或:

tell application "Safari"
    close (every tab of every window whose URL contains "some_text")
end tell