• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Add-on SDK
  5. Guides
  6. Contributor's Guide
  7. Modules

Modules

In This Article
  1. Loading Subscripts
  2. Exporting Names
  3. Importing Names
  4. Sandboxes and Compartments
  5. Modules in the Add-on SDK
  6. The Cuddlefish Loader

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

From Firefox 53 onwards, no new legacy add-ons will be accepted on addons.mozilla.org (AMO).

From Firefox 57 onwards, WebExtensions will be the only supported extension type, and Firefox will not load other types.

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to WebExtensions if they can. See the "Compatibility Milestones" document for more.

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

A module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. The use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. Unfortunately, JavaScript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. We will show how to do each of these things using the built-in Components object provided by Xulrunner application such as Firefox and Thunderbird.

To improve encapsulation, each module should be defined in the scope of its own global object. This is made possible by the use of sandboxes. Each sandbox lives in its own compartment. A compartment is a separate memory space. Each compartment has a set of privileges that determines what scripts running in that compartment can and cannot do. We will show how sandboxes and compartments can be used to improve security in our module system.

The module system used by the SDK is based on the CommonJS specification: it is implemented using a loader object, which handles all the bookkeeping related to module loading, such as resolving and caching URLs. We show how to create your own custom loaders, using the Loader constructor provided by the SDK. The SDK uses its own internal loader, known as Cuddlefish. All modules within the SDK are loaded using Cuddlefish by default. Like any other custom loader, Cuddlefish is created using the Loader constructor. In the final section, we will take a look at some of the options passed by the SDK to the Loader constructor to create the Cuddlefish loader.

Loading Subscripts

When a JavaScript project reaches a certain size, it becomes necessary to split it up into multiple files. Unfortunately, JavaScript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality. Applications such as Firefox and Thunderbird are based on Xulrunner. Xulrunner adds a built-in object, known as Components, to the global scope. This object forms the central access point for all functionality provided by the host application. A complete explanation of how to use Components is out of scope for this document. However, the following example shows how it can be used to load scripts from other locations:

const {
    classes: Cc
    interfaces: Ci
} = Components;
var instance = Cc["@mozilla.org/moz/jssubscript-loader;1"];
var loader = instance.getService(Ci.mozIJSSubScriptLoader);
function loadScript(url) {
    loader.loadSubScript(url);
}

When a script is loaded, it is evaluated in the scope of the global object of the script that loaded it. Any property defined on the global object will be accessible from both scripts:

index.js:
loadScript("www.foo.com/a.js");
foo; // => 3
a.js:
foo = 3;

Exporting Names

The script loader we obtained from the Components object allows us load scripts from other locations, but its API is rather limited. For instance, it does not know how to handle relative URLs, which is cumbersome if you want to organize your project hierarchically. A more serious problem with the loadScript function, however, is that it evaluates all scripts in the scope of the same global object. This becomes a problem when two scripts try to define the same property:

index.js:
loadScript("www.foo.com/a.js");
loadScript("www.foo.com/b.js");
foo; // => 5
a.js:
foo = 3;
b.js:
foo = 5;

In the above example, the value of foo depends on the order in which the subscripts are loaded: there is no way to access the property foo defined by "a.js", since it is overwritten by "b.js". To prevent scripts from interfering with each other, loadScript should evaluate each script to be loaded in the scope of their own global object, and then return the global object as its result. In effect, any properties defined by the script being loaded on its global object are exported to the loading script. The script loader we obtained from Components allows us to do just that:

function loadScript(url) {
    let global = {};
    loader.loadSubScript(url, global);
    return global;
}

If present, the loadSubScript function evaluates the script to be loaded in the scope of the second argument. Using this new version of loadScript, we can now rewrite our earlier example as follows:

index.js:
let a = loadScript("www.foo.com/a.js");
let b = loadScript("www.foo.com/b.js");
a.foo // => 3
b.foo; // => 5
a.js:
foo = 3;
b.js:
foo = 5;

Importing Names

In addition to exporting properties from the script being loaded to the loading script, we can also import properties from the loading script to the script being loaded:

function loadScript(url, imports) {
    let global = {
        imports: imports,
        exports: {}
    };
    loader.loadSubScript(url, global);
    return global.exports;
}

Among other things, this allows us to import loadScript to scripts being loaded, allowing them to load further scripts:

index.js:
loadScript("www.foo.com/a.js", {
    loadScript: loadScript
}).foo; => 5
a.js:
exports.foo = imports.loadScript("www.foo.com/b.js").bar;
b.js:
exports.bar = 5;

Sandboxes and Compartments

The loadScript function as defined in the previous section still has some serious shortcomings. The object it passed to the loadSubScript function is an ordinary object, which has the global object of the loading script as its prototype. This breaks encapsulation, as it allows the script being loaded to access the built-in constructors of the loading script, which are defined on its global object. The problem with breaking encapsulation like this is that malicious scripts can use it to get the loading script to execute arbitrary code, by overriding one of the methods on the built-in constructors. If the loading script has chrome privileges, then so will any methods called by the loading script, even if that method was installed by a malicious script.

To avoid problems like this, the object passed to loadSubScript should be a true global object, having its own instances of the built-in constructors. This is exactly what sandboxes are for. A sandbox is a global object that lives in a separate compartment. Compartments are a fairly recent addition to SpiderMonkey, and can be seen as a separate memory space. Objects living in one compartment cannot be accessed directly from another compartment: they need to be accessed through an intermediate object, known as a wrapper. Compartments are very useful from a security point of view: each compartment has a set of privileges that determines what a script running in that compartment can and cannot do. Compartments with chrome privileges have access to the Components object, giving them full access to the host platform. In contrast, compartments with content privileges can only use those features available to ordinary websites.

The Sandbox constructor takes a URL parameter, which is used to determine the set of privileges for the compartment in which the sandbox will be created. Passing an XUL URL will result in a compartment with chrome privileges (note, however, that if you ever actually do this in any of your code, Gabor will be forced to hunt you down and kill you). Otherwise, the compartment will have content privileges by default. Rewriting the loadScript function using sandboxes, we end up with:

function loadScript(url, imports) {
    let global = Components.utils.Sandbox(url);
    global.imports = imports;
    global.exports = {};
    loader.loadSubScript(url, global);
    return global.exports;
}

Note that the object returned by Sandbox is a wrapper to the sandbox, not the sandbox itself. A wrapper behaves exactly like the wrapped object, with one difference: for each property access/function it performs an access check to make sure that the calling script is actually allowed to access/call that property/function. If the script being loaded is less privileged than the loading script, the access is prevented, as the following example shows:

index.js:
let a = loadScript("www.foo.com/a.js", {
    Components: Components
});
// index.js has chrome privileges
Components.utils; // => [object nsXPCComponents_Utils]
a.js:
// a.js has content privileges
imports.Components.utils; // => undefined

Modules in the Add-on SDK

The module system used by the SDK is based on what we learned so far: it follows the CommonJS specification, which attempts to define a standardized module API. A CommonJS module defines three global variables: require, which is a function that behaves like loadScript in our examples, exports, which behaves like the exports object, and module, which is an object representing the module itself. The require function has some extra features not provided by loadScript: it solves the problem of resolving relative URLs (which we have left unresolved), and provides a caching mechanism, so that when the same module is loaded twice, it returns the cached module object rather than triggering another download. The module system is implemented using a loader object, which is actually provided as a module itself. It is defined in the module “toolkit/loader”:

const { Loader } = require('toolkit/loader')

The Loader constructor allows you to create your own custom loader objects. It takes a single argument, which is a named options object. For instance, the option paths is used to specify a list of paths to be used by the loader to resolve relative URLs:

let loader = Loader({
    paths: ["./": "http://www.foo.com/"]
});

CommonJS also defines the notion of a main module. The main module is always the first to be loaded, and differs from ordinary modules in two respects. Firstly, since they do not have a requiring module. Instead, the main module is loaded using a special function, called main:

const { Loader, main } = require('toolkit/loader');
let loader = Loader({
    paths: ["./": "http://www.foo.com/"]
});
main(loader, "./main.js");
Secondly, the main module is defined as a property on require. This allows modules to check if they have been loaded as the main module:
 
function main() {
    ...
}
if (require.main === module)
    main();

The Cuddlefish Loader

The SDK uses its own internal loader, known as Cuddlefish (because we like crazy names). Like any other custom loader, Cuddlefish is created using the Loader constructor: Let's take a look at some of the options used by Cuddlefish to customize its behavior. The way module ids are resolved can be customized by passing a custom resolve function as an option. This function takes the id to be resolved and the requiring module as an argument, and returns the resolved id as its result. The resolved id is then further resolved using the paths array:

const { Loader, main } = require('toolkit/loader');
let loader = Loader({
    paths: ["./": "http://www.foo.com/"],
    resolve: function (id, requirer) {
        // Your code here
        return id;
    }
});
main(loader, "./main.js");

Cuddlefish uses a custom resolve function to implement a form of access control: modules can only require modules for which they have been explicitly granted access. A whitelist of modules is generated statically when the add-on is linked. It is possible to pass a list of predefined modules as an option to the Loader constructor. This is useful if the API to be exposed does not have a corresponding JS file, or is written in an incompatible format. Cuddlefish uses this option to expose the Components object as a module called chrome, in a way similar to the code here below:

const {
    classes: Cc,
    Constructor: CC,
    interfaces: Ci,
    utils: Cu,
    results: Cr,
    manager: Cm
} = Components;
let loader = Loader({
    paths: ["./": "http://www.foo.com/"],
    resolve: function (id, requirer) {
        // Your logic here
        return id;
    },
    modules: {
        'chrome': {
            components: Components,
            Cc: Cc,
            CC: bind(CC, Components),
            Ci: Ci,
            Cu: Cu,
            Cr: Cr,
            Cm: Cm
        }
    }
});

All accesses to the chrome module go through this one point. As a result, we don't have to give modules chrome privileges on a case by case basis. More importantly, however, any module that wants access to Components has to explicitly express its intent via a call to require("chrome"). This makes it possible to reason about which modules have chrome capabilities and which don't.

Document Tags and Contributors

Tags: 
  • Add-ons
  • Extensions
 Contributors to this page: wbamberg, maybe, evold
 Last updated by: wbamberg, Nov 30, 2016, 2:06:38 PM
See also
  1. WebExtensions
  2. Getting started
    1. What are WebExtensions?
    2. Your first WebExtension
    3. Your second WebExtension
    4. Anatomy of a WebExtension
    5. Example WebExtensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. Concepts
    1. Using the JavaScript APIs
    2. User interface components
    3. Content scripts
    4. Match patterns
    5. Internationalization
    6. Content Security Policy
    7. Native messaging
  5. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox add-on
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
  6. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Getting started with web-ext
    4. web-ext command reference
    5. WebExtensions and the Add-on ID
    6. Publishing your WebExtension
  7. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. downloads
    11. events
    12. extension
    13. extensionTypes
    14. history
    15. i18n
    16. identity
    17. idle
    18. management
    19. notifications
    20. omnibox
    21. pageAction
    22. runtime
    23. sessions
    24. sidebarAction
    25. storage
    26. tabs
    27. topSites
    28. webNavigation
    29. webRequest
    30. windows
  8. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_url_overrides
    6. commands
    7. content_scripts
    8. content_security_policy
    9. default_locale
    10. description
    11. developer
    12. homepage_url
    13. icons
    14. manifest_version
    15. name
    16. omnibox
    17. options_ui
    18. page_action
    19. permissions
    20. short_name
    21. sidebar_action
    22. version
    23. web_accessible_resources
  9. Add-on SDK
  10. Getting started
    1. Installation
    2. Getting started
    3. Troubleshooting
  11. High-Level APIs
    1. addon-page
    2. base64
    3. clipboard
    4. context-menu
    5. hotkeys
    6. indexed-db
    7. l10n
    8. notifications
    9. page-mod
    10. page-worker
    11. panel
    12. passwords
    13. private-browsing
    14. querystring
    15. request
    16. selection
    17. self
    18. simple-prefs
    19. simple-storage
    20. system
    21. tabs
    22. timers
    23. ui
    24. url
    25. webextension
    26. widget
    27. windows
  12. Low-Level APIs
    1. /loader
    2. chrome
    3. console/plain-text
    4. console/traceback
    5. content/content
    6. content/loader
    7. content/mod
    8. content/symbiont
    9. content/worker
    10. core/heritage
    11. core/namespace
    12. core/promise
    13. dev/panel
    14. event/core
    15. event/target
    16. frame/hidden-frame
    17. frame/utils
    18. fs/path
    19. io/byte-streams
    20. io/file
    21. io/text-streams
    22. lang/functional
    23. lang/type
    24. loader/cuddlefish
    25. loader/sandbox
    26. net/url
    27. net/xhr
    28. places/bookmarks
    29. places/favicon
    30. places/history
    31. platform/xpcom
    32. preferences/event-target
    33. preferences/service
    34. remote/child
    35. remote/parent
    36. stylesheet/style
    37. stylesheet/utils
    38. system/child_process
    39. system/environment
    40. system/events
    41. system/runtime
    42. system/unload
    43. system/xul-app
    44. tabs/utils
    45. test/assert
    46. test/harness
    47. test/httpd
    48. test/runner
    49. test/utils
    50. ui/button/action
    51. ui/button/toggle
    52. ui/frame
    53. ui/id
    54. ui/sidebar
    55. ui/toolbar
    56. util/array
    57. util/collection
    58. util/deprecate
    59. util/list
    60. util/match-pattern
    61. util/object
    62. util/uuid
    63. window/utils
  13. Firefox for Android
  14. Getting started
    1. Walkthrough
    2. Debugging
    3. Code snippets
  15. APIs
    1. Accounts.jsm
    2. BrowserApp
    3. HelperApps.jsm
    4. Home.jsm
    5. HomeProvider.jsm
    6. JavaAddonManager.jsm
    7. NativeWindow
    8. Notifications.jsm
    9. PageActions.jsm
    10. Prompt.jsm
    11. RuntimePermissions.jsm
    12. Snackbars.jsm
    13. Sound.jsm
    14. Tab
  16. Legacy
  17. Restartless extensions
    1. Overview
  18. Overlay extensions
    1. Overview
  19. Themes
  20. Lightweight themes
    1. Overview
  21. Complete themes
    1. Overview
  22. Publishing add-ons
  23. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Review policies
    4. Developer agreement
    5. Featured add-ons
    6. Contact addons.mozilla.org
  24. Community and support
  25. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel