Search code examples
javascriptfirefox-addon-sdk

Access custom functions within the Firefox Addon SDK main.js file?


Why can't I access custom functions with the Firefox Addon SDK?

In my example code below, clicking context menu Sub Item 1 doesn't work; It refers to custom function verifyTest() but returns a ReferenceError: verifyTest is undefined. Clicking Sub Item 2 which directs to built-in function alert() works well.

I also tried with self.postMessage (and onMessage) but no success.. What do I have to do to access (or define) my custom functions that are required for my addon to work?

///// Content in main.js

function verifyTest() {
    alert('test1');
}

var script1 = 'self.on("click", function(node, data){'+
             '   verifyTest();'+
             '});';

var script2 = 'self.on("click", function(){'+
             '   alert(\'test2\');'+
             '});';

var cm = require("sdk/context-menu");
cm.Menu({
  label: "Main Item",
  context: cm.SelectorContext("body"),
  items: [
    cm.Item({ label: "Sub Item 1", context: cm.SelectorContext("input[type=text]"), contentScript: script1, data: "item1" }),
    cm.Item({ label: "Sub Item 2", context: cm.SelectorContext("input[type=text]"), contentScript: script2, data: "item2" })
  ]
});

Solution

  • Because verifyTest is defined in the context of main.js not script1.

    One solution is to put verifyTest inside script1 (as quoted text).

    A better solution would be to create a file script1.js (or other meaningful name) with this content:

    function verifyTest() {
        alert('test1');
    }
    
    self.on("click", function(node, data){
        verifyTest();
    });
    

    and use contentScriptFile instead of contentScript to load it (see Loading Content Scripts).

    cm.Item({ label: "Sub Item 1", context: cm.SelectorContext("input[type=text]"), contentScriptFile: require("sdk/self").data.url("script1.js"), data: "item1" }),
    

    This makes it more readable and maintainable and avoids bugs of using vars/functions defined in different contexts.