5

我知道当我进入 mozrepl 会话时,我处于一个特定浏览器窗口的上下文中。在那个窗口我可以做

var tabContainer = window.getBrowser().tabContainer;
var tabs = tabContainer.childNodes;

这将在该窗口中为我提供一系列选项卡。我需要在所有打开的 Firefox 窗口中获取所有选项卡的数组,我该怎么做?

4

1 回答 1

4

我不确定它是否可以在 mozrepl 中工作,但在 Firefox 插件中,您可以执行类似以下代码的操作。此代码将循环浏览所有打开的浏览器窗口。在这种情况下doWindow,为每个窗口调用一个函数。

Components.utils.import("resource://gre/modules/Services.jsm");
function forEachOpenWindow(fn)  {
    // Apply a function to all open browser windows

    var windows = Services.wm.getEnumerator("navigator:browser");
    while (windows.hasMoreElements()) {
        fn(windows.getNext().QueryInterface(Ci.nsIDOMWindow));
    }
}

function doWindow(curWindow) {
    var tabContainer = curWindow.getBrowser().tabContainer;
    var tabs = tabContainer.childNodes;
    //Do what you are wanting to do with the tabs in this window
    //  then move to the next.
}

forEachOpenWindow(doWindow);

您可以创建一个包含所有当前选项卡的数组,只需doWindow将其获取的任何选项卡添加tabContainer.childNodes到整个列表即可。我在这里没有这样做,因为您从中获得的tabContainer.childNodes实时集合,并且您没有说明您是如何使用该数组的。您的其他代码可能会或可能不会假设该列表是实时的。

如果您绝对希望所有选项卡都在一个数组中,则doWindow可以是以下内容:

var allTabs = [];
function doWindow(curWindow) {
    var tabContainer = curWindow.getBrowser().tabContainer;
    var tabs = tabContainer.childNodes;
    //Explicitly convert the live collection to an array, then add to allTabs
    allTabs = allTabs.concat(Array.prototype.slice.call(tabs));
}

注意:循环窗口的代码最初取自将旧的基于覆盖的 Firefox 扩展转换为无需重启的插件,作者将其重写为如何在 MDN上将覆盖扩展转换为无重启的初始部分。

于 2015-06-24T21:14:44.890 回答