Search code examples
javascriptfirefoxfirefox-addonmozilla

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 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.


Solution

  • 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.