开发者

How to trigger an event from injected HTML button in firefox extension?

My end goal is to create a firefox extension that inserts an HTML button onto a 开发者_StackOverflow中文版site and have it fire a function defined in a custom code module in my extension.

I tried to implement Nickolay's answer to this question. When I click the button I created though I get the following error in Firebug:

"uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIDOMEventTarget.dispatchEvent]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: "

My code:

onPageLoad: function(aEvent) {
    Components.utils.import("chrome://my_ext/content/writeFile.jsm", my_ext);
    //alert(foo());  - foo() is an function in the above code module I import


    var doc = aEvent.originalTarget; // doc is document that triggered "onload" event

    var event = doc.createEvent("Events");
    event.initEvent("my-custom-event", true, true);

    var fblike = doc.getElementById("LikePluginPagelet");
    var button = doc.createElement("input");
    button.setAttribute("type", "button");
    button.setAttribute("value", "My Button");
    button.setAttribute('onclick', 'dispatchEvent(event)');

    fblike.appendChild(button, fblike);

    var docx = event.originalTarget;
    if(docx && docx.addEventListener)
        docx.addEventListener("my-custom-event", function() {alert(foo()); }, false);
},

My writeFile.jsm:

var EXPORTED_SYMBOLS = ["foo"];

function foo() {
    return "foo test";
}

Any idea on how I can fix this? I should also mention that I am completely new to developing browser extensions.


button.setAttribute('onclick', 'dispatchEvent(event)') will not do what you think it will do - when the button is clicked it takes the click event and tries to dispatch it. Dispatching an event a second time isn't allowed however. What you seem to want is this:

button.addEventListener("click", function() {
  button.dispatchEvent(event);
}, false);

This creates a function closure that will have access to the variable of the surrounding code - including button and event. Further reading on closures: http://www.javascriptkit.com/javatutors/closures.shtml


Finally got it to work. I did not need to add the second listener and it only took one line: button.addEventListener("click", foo, false);

I had previously tried foo() instead of just foo and that failed but works just fine now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜