How to listen to page loads from Fennec extension?

血红的双手。 提交于 2020-01-03 17:51:09

问题


I'm working on a simple extension for Fennec, which must add special HTML element to every loaded page. I've created this simple overlay.js:

var MyAddon = {
    onLoad: function(aEvent){
        var appcontent = document.getElementById("appcontent"); // Firefox
        if (!appcontent) {
            appcontent = document.getElementById("browsers"); // Fennec
        }
        if (appcontent) {
            appcontent.addEventListener("DOMContentLoaded", MyAddon.onDocumentLoad, true);
        }
    },

    onUnLoad: function(aEvent){
        var appcontent = document.getElementById("appcontent"); // Firefox
        if (!appcontent) {
            appcontent = document.getElementById("browsers"); // Fennec
        }
        if (appcontent) {
            appcontent.removeEventListener("DOMContentLoaded", MyAddon.onDocumentLoad, true);
        }
    },

    onUIReady: function(aEvent){
    },

    onUIReadyDelayed: function(aEvent) {
    },

    onDocumentLoad: function(aEvent) {
    alert("OK");
    }
};

window.addEventListener("load", MyAddon.onLoad, false);
window.addEventListener("unload", MyAddon.onUnLoad, false);
window.addEventListener("UIReady", MyAddon.onUIReady, false);
window.addEventListener("UIReadyDelayed", MyAddon.onUIReadyDelayed, false);

The problem is that alert is shown only one time when browser is started, I'd expect it to show on every page that loads. What am I doing wrong?

Fennec version: 4.0b5 (testing on Desktop version for Windows)

Thanks!


回答1:


Unfortunately, this is more complex for Fennec. There is no such event as "DOMContentLoaded" coming from the content document. This is because the main window, where your overlay attached the Javascript, lives in a different process than the child windows (content windows)

You have to:

  1. load a script with each new tab:

    browser.messageManager.loadFrameScript("chrome://my_add_on/content/content.js", true);

  2. Inside content.js, listen to the event DOMContentLoaded:

    addEventListener("DOMContentLoaded", process, true); function process(event) { ... }

For more info, check this pages:

  • https://wiki.mozilla.org/Mobile/Fennec/Extensions/Electrolysis
  • https://hg.mozilla.org/mobile-browser/file/8167d57cab8e/chrome/content/browser.js#l1327


来源:https://stackoverflow.com/questions/5180634/how-to-listen-to-page-loads-from-fennec-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!