Search code examples
firefox-addonfirefox-addon-sdk

How do I share javascript code between background and content scripts in Firefox Jetpack add-ons?


I've written a library to mimic Chrome's request/response API for my Firefox add-on. Obviously I need to use this code in both my background process (main.js) and my content script. Surely there must be a better way than stringifying the imported module.


Solution

  • There is a semi-documented way of getting the URLs of the SDK code modules. This involves low-level modules which aren't guaranteed to stay stable. In fact, it is very likely that this part of the SDK will change and this solution won't work any more (like the solution originally presented here).

    That said, the SDK allows you to access the loader module. So first you need to construct a loader with the same options as the one used by the SDK. Then you need to use the resolveURI utility function to resolve the module name using the mapping of this loader:

    var {Loader, resolveURI} = require('toolkit/loader');
    var options = require('@loader/options');
    var loader = Loader(options);
    var fooURI = resolveURI("./foo", loader.mapping);
    

    The code above generates the URL for the module foo. Note that you need to use the module foo somewhere, otherwise it won't be included in your extension. If you don't use it yet then a dummy function will be sufficient:

    function dummy()
    {
      require("foo");
    }
    

    Using the resulting URL as content script works just fine:

    var pageMod = require("page-mod");
    pageMod.PageMod({
      include: "*.google.com",
      contentScriptWhen: 'end',
      contentScriptFile: [fooURI, ...]
    });