xpcom / jetpack观察所有文档加载

时间:2010-07-04 16:15:58

标签: firefox-addon document observer-pattern xpcom firefox-addon-sdk

我编写了一个基于Mozilla Jetpack的附加组件,只要加载文档就必须运行该附加组件。对于“顶级文档”,这主要使用此代码(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);

但是当用户使用中间点击或(更重要的是!)为框架打开新选项卡时,不会调用回调。甚至这个话题我只是通过阅读另一个扩展的来源,而不是通过文档。

那么如何注册每次加载文档时都会调用的回调?

编辑:这似乎符合我的要求:

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

部分来自此处:https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads

2 个答案:

答案 0 :(得分:0)

@ kizzx2你最好用#jetpack

服务

原始问题:为什么不使用tab-browser模块。像这样:

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

比你做的更清洁恕我直言和(直到我们有官方的pageMods模块)支持的方式如何做到这一点。

答案 1 :(得分:0)

从Addon SDK 1.0开始,正确的方法是使用page-mod模块。

(在引擎盖下,它是使用document-element-inserted观察者服务通知实现的,您可以在常规扩展中使用它,或者如果page-mod不适合您。)

相关问题