Search code examples
javascriptfirefoxfirefox-addondom-events

Unable to call Firefox extension function from page Javascript


I have an XUL extension with different document object, perhaps that is why the following doesn't work:

In my page Javascript:

var evt = document.createEvent("Events");
evt.initEvent("JSON_UPDATE_EVENT", true, false);
document.dispatchEvent(evt);

In extension, the main.js file:

document.addEventListener("JSON_UPDATE_EVENT", alert("hello"), false, true);

I even tried tried:

Application.activeWindow.activeTab.document.addEventListener("JSON_UPDATE_EVENT", alert("hello"), false, true);

In both the cases the alert() is called only once when the extension is started, but never on the event. The document in web page and extension refer to different objects, that might be the reason perhaps.


Solution

  • in the main.js file do this:

    var chromeWindow = Services.wm.getMostRecentWindow('navigator:browser');
    function rawr() { 
    chromeWindow.alert("hello")
    }
    chromeWindow.gBrowser.addEventListener("JSON_UPDATE_EVENT", rawr, false, true);
    

    each window with tabs has its own gBrowser.

    if you want to add this to all currently open windows, and all future windows that open see this template here: https://gist.github.com/Noitidart/8673632

    use the template and just edit inside addDiv and removeDiv