mozrepl: loop through all tabs in all windows of firefox

1.1k views Asked by At

I know that when I enter a mozrepl session I'm in the context of one particular browser window. In that 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 the tabs in all open Firefox windows, how do I do that?

1

There are 1 answers

0
Makyen On BEST ANSWER

I'm not sure it will work in mozrepl, but within a Firefox add-on, you could do something like the following code. This code will cycle through all open browser windows. A 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 could create an array that contains all of the current tabs by just having doWindow add any tabs that it obtains from tabContainer.childNodes to an overall list. I have not done that here because what you obtain from tabContainer.childNodes is a live collection and you have not stated how you are using the array. Your other code may, or may not, be assuming that the list is live.

If you definitely want all of the tabs to be in one array, you could have doWindow be the following:

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 to loop through windows was originally taken from 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 on MDN.