0

I have simple Firefox extension (based on Add-on SDK) with pageMod. pageMod injects some script to a page, which calls one function:

function dispatchEvent(name, data){
    try {
        data = data || {};
        // passing some data through html element
        document.getElementById('MyDiv').innerText = JSON.stringify(data);
        var evt = document.createEvent('Event');
        evt.initEvent(name.toString(), true, true);
        if(document.getElementById('MyDiv').dispatchEvent(evt))
            console.log("Dispatch event: "+name+" data: "+JSON.stringify(data));
    } catch (e) {
        console.log("Error:" + e);
    }
}
dispatchEvent("MyEvent", {});

On the web page I have event listener, added through MyDiv.addEventListener(...). Problem is the injected script does not dispatch any event to a page. The dispatchEvent function returns true, but nothing happens. Here is my pageMod code:

var myMod = pageMod.PageMod({
    include: ["http://localhost/mysite/*"],
    contentScriptFile: [data.url("js/script.js")],
    contentScriptWhen: "end",
    onAttach: function onAttach(worker) {
          console.log("CS injected");
    }
});

If I run contentScript code through Firebug console, it works, but I need to dispatch events from contentScript.

P.S. I also tried to use unsafeWindow.document instead of document, and use jQuery events/event listeners and it's not working either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • If you replace `innerText` (which is MSIE-only) by `textContent`, is the data being set correctly? On the first glance, I don't see anything wrong with your code, it should work. – Wladimir Palant Sep 30 '11 at 10:49
  • Data is set correctly. There is problem with event dispatching. Actually, event listener on the page does not catch the event, sent from content script. – Sergey Galchenko Sep 30 '11 at 10:56
  • It should - sending events from trusted to untrusted code is explicitly allowed. Are you certain that the event listener on the page is registered correctly? What if you send an event from the page itself, is it received? – Wladimir Palant Sep 30 '11 at 11:10
  • Yes, I wrote above, that if I run contentScript code from firebug console it works fine. – Sergey Galchenko Sep 30 '11 at 11:31

1 Answers1

1

I took time to convert your question into a testcase, and it works for me: https://builder.addons.mozilla.org/addon/1018586/revision/13/

Please provide the complete testcase the next time, as the problem often lies not in the piece of code you think it does.

Nickolay
  • 31,095
  • 13
  • 107
  • 185