开发者

Add-on SDK calling dispatchEvent does not send event from content script to a page

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))
            conso开发者_如何学运维le.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜