2010-08-21 99 views
3

运行我的一些脚本后,我碰巧遇到了一堆有“无标题”窗口的Safari窗口。使用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

使用一个AppleScript filter reference form

tell application "Safari" 
    close (every window whose name is "Untitled") 
end tell 
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"语法),但这似乎工作。

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