views:

28

answers:

1

I write a Mozilla Jetpack based add-on that has to run whenever a document is loaded. For "toplevel documents" this mostly works using this code (OserverService = require('observer-service')):

    this.endDocumentLoadCallback = function (subject, data) {
        console.log('loaded: '+subject.location);
        try {
            server.onEndDocumentLoad(subject);
        }
        catch (e) {
            console.error(formatTraceback(e));
        }
    };
    ObserverService.add("EndDocumentLoad", this.endDocumentLoadCallback);

But the callback doesn't get called when the user opens a new tab using middle click or (more importantly!) for frames. And even this topic I only got through reading the source of another extension and not through the documentation.

So how do I register a callback that really gets called every time a document is loaded?

Edit: This seems to do what I want:

function callback (event) {
    // this is the content document of the loaded page.
    var doc = event.originalTarget;

    if (doc instanceof Ci.nsIDOMNSHTMLDocument) {
        // is this an inner frame?
        if (doc.defaultView.frameElement) {
            // Frame within a tab was loaded.
            console.log('!!! loaded frame:',doc.location.href);
        }
        else {
            console.log('!!! loaded top level document:',doc.location.href);
        }
    }
}

var wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
mainWindow.gBrowser.addEventListener("load", callback, true);

Got it partially from here: https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads

A: 

@kizzx2 you are better served with #jetpack

To the original question: why don't you use tab-browser module. Something like this:

var browser = require("tab-browser");

exports.main = function main(options, callbacks) {
initialize(function (config) {
    browser.whenContentLoaded(
        function(window) {
           // something to do with the window
           // e.g., if (window.locations.href === "something")
        }
    );
});

Much cleaner than what you do IMHO and (until we have official pageMods module) the supported way how to do this.

mcepl
I haven't tried it but I guess I don't get page loads that aren't initiated by me this way. E.g. loads of frames and popups. I need to observe all loads.
panzi
Yes, this is just for new tabs.
mcepl