Mozrepl: iterate over all tabs in all firefox windows

I know that when I enter a mozrepl session, I enter the context of one specific browser window. In this window, I can do

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

      

which will give me an array of tabs in that window. I need to get an array of all tabs in all open Firefox windows, how do I do this?

+3


source to share


1 answer


I'm not sure if it will work in mozrepl, but in addition to Firefox, you can do something like the following code. This code will go through all open browser windows. The function, in this case doWindow

, is called for each window.

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);

      

You can create an array containing all the current tabs by simply adding doWindow

add all the tabs received from tabContainer.childNodes

to the general list. I didn't do this here because what you are getting from tabContainer.childNodes

is a live collection and you haven't specified how you are using the array. Your other code may or may not be, consider that this list is live.



If you definitely want all tabs to be in the same array, you could have doWindow

this:

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));
}

      

Note. The code for scrolling windows was originally taken from Converting an old Firefox overlay extension to a non-repeatable add-on , which the author rewrote as the initial part of How to convert an overlay extension to without restarting on MDN.

+4


source







All Articles