mozrepl:遍历所有 windows 的 firefox 中的所有选项卡

mozrepl: loop through all tabs in all windows of firefox

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

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

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

我不确定它能否在 mozrepl 中运行,但在 Firefox 附加组件中,您可以执行类似以下代码的操作。此代码将循环遍历所有打开的浏览器 windows。为每个 window.

调用一个函数,在本例中为 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 获得的是一个 live collection 并且您没有说明您如何使用该数组。您的其他代码可能会或可能不会假设该列表是实时的。

如果您确实希望所有选项卡都在一个数组中,您可以 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));
}

注:循环遍历windows的代码最初取自MDN上的Converting an old overlay-based Firefox extension into a restartless addon which the author re-wrote as the initial part of How to convert an overlay extension to restartless