javascriptfirefoximportfirefox-addonadd-on

Mozilla FireFox Addons -> Include external library in main.js


I need to import/include a javascript file in my main.js in my FireFox Addon, but as the main.js does not contain a "document" I can not insert it the normal/easy way.

I've tried some stuff but never got it working.

Here is what I exactly want to accomplish: I use an external timezone detection script (https://bitbucket.org/pellepim/jstimezonedetect/overview). I need to determine the timezone in the main.js to download the Google Calendar File + convert the times to the users timezone. This can not be done later! Until now I just inserted the code manually into the file (copy+paste), but this is not a very nice and clear way of doing this.


Solution

  • You would need to create a CommonJS module. Add your .js file inside the addon's lib folder and export all functions that you will be needing via the "exports" directive. Once you do that, you can use the exported functions via the "require" directive.

    For example in the module that you will be reusing, you can put:

    // REUSABLE MODULE
    exports.somefunction = somefunction;
    
    function somefunction() {
        doSomething();
     }
    

    And then in the module that will be using this:

    var othermodule = require("reusable_module");
    othermodule.somefunction();
    

    Here is the relevant documentation: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/modules.html