2010-08-21 98 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