2

我制作了一个非常简单的 AppleScript 来关闭 Safari 中的选项卡。问题是,它有效,但不完全有效。只关闭了几个选项卡。这是代码:

tell application "Safari"
    repeat with aWindow in windows
        repeat with aTab in tabs of aWindow
            if [some condition is encountered] then
                aTab close
            end if
        end repeat
    end repeat
end tell

我也试过这个脚本:

tell application "Safari"
    repeat with i from 0 to the number of items in windows
        set aWindow to item i of windows
        repeat with j from 0 to the number of tabs in aWindow
            set aTab to item j of tabs of aWindow
            if [some condition is encountered] then
                aTab close
            end if
        end repeat
    end repeat
end tell

...但它也不起作用(相同的行为)。

我在我的系统(2008 年 1 月的 MacBook Pro)以及 Tiger 下的 Mac Pro G5 上进行了尝试,但脚本在两者上都失败了,尽管 Tiger 上的描述性错误要少得多。

运行脚本几次每次都会关闭几个选项卡,直到没有留下任何选项卡,但在关闭几个选项卡后总是失败并出现相同的错误。在 Leopard 下,我得到一个越界错误。由于我使用的是快速枚举(不使用“从 0 到 Windows 中的项目数重复”),所以我不知道如何获得越界错误...

我的目标是使用 Cocoa Scripting Bridge 从我的 Objective-C Cocoa 应用程序中关闭 Safari 中的选项卡,但 Scripting Bridge 以同样的方式失败。不可删除的选项卡显示NULL在 Xcode 调试器中,而其他选项卡是有效对象,我可以从中获取值(例如它们的标题)。事实上,我首先尝试了 Scripting Bridge,然后告诉自己为什么不直接在 AppleScript 中尝试,我很惊讶地看到了相同的结果。

我必须有一个明显的遗漏或那里的东西......(对我来说,这似乎是Safari AppleScript支持中的一个错误......:S)我使用重复循环和Obj-C 2.0快速枚举来迭代集合之前为零问题,所以我真的看不出这里有什么问题。

任何人都可以帮忙吗?

提前致谢!

4

3 回答 3

7

我有一个脚本可以关闭所有选项卡但不需要重复循环。

set closeTab to "Stack Overflow" as string
tell application "Safari"
    close (every tab of window 1 whose name is not equal to closeTab)
end tell

看看这是否适合你。

注意:将“堆栈溢出”更改为您想要保持打开状态的选项卡的任何标题名称。

于 2010-03-23T22:41:47.947 回答
5

这对我来说很好很简单

  tell application "Safari"
    close every window
  end tell

好的,您必须从计数变为 1,否则当您关闭窗口时计数将关闭

  tell application "Safari"
    repeat with i from (count of windows) to 1 by -1
        repeat with j from (count of tabs of window i) to 1 by -1
            set thistab to tab j of window i
            set foo to name of thistab
            if foo is not equal to "bar" then close thistab
        end repeat
    end repeat
  end tell
于 2010-03-23T20:34:04.370 回答
0

两个提供的答案都很好,但我认为最好将两者结合起来。这样,您将关闭所有 chrome 窗口的所有选项卡,并且它比第一个答案更简洁:

set closeTab to  "Post Attendee" as string
tell application "Google Chrome"
    repeat with i from (count of windows) to 1 by -1
          close (every tab of window i whose name is not equal to closeTab)
    end repeat
end tell
于 2021-02-08T16:19:06.667 回答