.gBrowser is undefined

1.9k Views Asked by At

I'm writing a restartless Firefoxextension where I have to enumerate all open tabs and work with them.

Here's the code-part that throws the error:

getInfoString : function ()
    {
        infos = "";
        HELPER.alerting("url", "URL-Function");
        var winMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
        HELPER.alerting("url", "Mediator initialized");
        var mrw = winMediator.getEnumerator(null);
        while(mrw.hasMoreElements())
        {
            var win = mrw.getNext();
            var t = win.gBrowser.browsers.length;
            HELPER.alerting("url", "browsers: " + t);
            for (var i = 0; i < t; i++)
            {
                var b = win.gBrowser.getBrowserAtIndex(i);
                if(b.currentURI.spec.substr(0,3) != "http")
                {
                    continue;
                }
                HELPER.alerting(b.title,b.currentURI.spec);
                var doc = b.contentDocument;
                var src = doc.documentElement.innerHTML;
                infos = infos + src
                HELPER.alerting("doc", src);
            }
        }

        return infos;
    }

I have a JavascriptDebugger-Addon running while testing this and Firefox executes everything fine to the line

HELPER.alerting("url", "browsers: " + t);

But AFTER this line, the debugger-addons throws an error, saying that:

win.gBrowser is undefined

... pointing to the line:

var t = win.gBrowser.browsers.length;

But before it throws the error I get my alertmessage which gives me the correct number of tabs. So the error is thrown after the line was executed and not directly WHEN it was executed. Does anyone has an idea how to fix this, because the extension stops working after the error has been thrown.

Greetz

P.S.: If someone has a better headline for this, feel free to edit it.

2

There are 2 best solutions below

0
On

Using winMediator.getEnumerator(null) would give you all types of window, that may or may not be browser windows. You should try changing the following line

var mrw = winMediator.getEnumerator(null);

with

var mrw = winMediator.getEnumerator('navigator:browser');
5
On

I finally figured out that this behavior can happen sometimes. I just rearranged the code a bit, removing some alerts inside the for-loop and it works just fine again. So if someone has this error too, just rearrange your code and it should work like a charm again.