Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

include own module does not work with firefox sdk require


for some reasons the following does code not work:

main.js:

var data = require('self').data;
var {Cc, Ci} = require('chrome');
var mediator = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
var self = require('self');

exports.main = function(options, callbacks)
{
    var tabs = require('sdk/tabs');

    tabs.on("ready",
            function (activeTab)
            {
                activeTab.attach({contentScriptFile: [self.data.url("inject.js")]});
            }
        );
};

inject.js:

var test = require("test");
test.five();

test.js under root-addon-folder/lib:

exports.five = function ()
{
    window.alert("high five!");
};

reference to the turiral here: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/reusable-modules.html with newest changes: http://blog.mozilla.org/addons/2013/01/25/changes-to-require-syntax/

I am using the online Builder from Mozilla.


Solution

  • Your inject.js is a content script. Content scripts cannot use require, only privileged modules such as main.js can.

    There is no equivalent require mechanism for content scripts, but you can load script from multiple data files at once.

    Just remove the exports bit from test.js, and place the file in the data folder:

    function five() {
        window.alert("high five!");
    }
    

    Then change your attach call:

    activeTab.attach({contentScriptFile: [
      self.data.url("test.js"),
      self.data.url("inject.js")
    ]});