mozrepl:循环浏览firefox所有窗口中的所有选项卡

mozrepl: loop through all tabs in all windows of firefox

本文关键字:选项 窗口 浏览 firefox mozrepl 循环      更新时间:2023-09-26

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

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

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

我不确定它是否能在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扩展转换为一个无restartless插件,作者重新编写了该插件,作为如何在MDN上将覆盖扩展转换为无restartless的初始部分