Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

JavaScript code modules are a concept introduced in Gecko 1.9 and can be used for sharing code between different privileged scopes. Modules can also be used to create global JavaScript singletons that previously required using JavaScript XPCOM objects. A JavaScript code module is simply some JavaScript code located in a registered location. The module is loaded into a specific JavaScript scope, such as XUL script or JavaScript XPCOM script, using Components.utils.import() or Components.utils["import"]().

Creating a JavaScript code module

A very simple JavaScript module looks like this:

var EXPORTED_SYMBOLS = ["foo", "bar"];

function foo() {
  return "foo";
}

var bar = {
  name : "bar",
  size : 3
};

var dummy = "dummy";

Notice that the module uses normal JavaScript to create functions, objects, constants, and any other JavaScript type. The module also defines a special Array named EXPORTED_SYMBOLS. Any JavaScript item named in EXPORTED_SYMBOLS will be exported from the module and injected into the importing scope. For example:

Components.utils.import("resource://app/my_module.jsm");

alert(foo());         // displays "foo"
alert(bar.size + 3);  // displays "6"
alert(dummy);         // displays "dummy is not defined" because 'dummy' was not exported from the module
Note: When you're testing changes to a code module, be sure to change the application's build ID (e.g., the version) before your next test run; otherwise, you may find yourself running the previous version of your module's code.

The URL for a code module

As you can see from the example above, you need a URL to import a code module. (The URL in the example is "resource://app/my_module.jsm".)

Code modules can only be loaded using a chrome: (), resource:, or file: URL.

  • If you're writing an extension for Firefox 4 and already have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm.
  • If your extension or application needs to support Mozilla 1.9.x (Firefox 3.x), you should register a new resource URL. Details on doing this are in the "Extending resource: URLs" section below.

Sharing objects using code modules

An extremely important behavior of Components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version. This means that a given module will be shared when imported multiple times. Any modifications to data, objects, or functions will be available in any scope that has imported the module. For example, if the simple module were imported into two different JavaScript scopes, changes in one scope can be observed in the other scope.

Scope 1:

Components.utils.import("resource://app/my_module.jsm");

alert(bar.size + 3);  // displays "6"

bar.size = 10;

Scope 2:

Components.utils.import("resource://app/my_module.jsm");

alert(foo());         // displays "foo"
alert(bar.size + 3);  // displays "13"

This sharing behavior can be used to create singleton objects that can share data across windows and between XUL script and XPCOM components.

Note: Each scope that imports a module receives a by-value copy of the exported symbols in that module. Changes to the symbol's value will not propagate to other scopes (though an object's properties will be manipulated by reference).

Scope 1:

Components.utils.import("resource://app/my_module.jsm");

bar = "foo";
alert(bar);         // displays "foo"

Scope 2:

Components.utils.import("resource://app/my_module.jsm");

alert(bar);         // displays "[object Object]"

The main effect of the by-value copy is that global variables of simple types won't be shared across scopes. Always put variables in a wrapper class and export the wrapper (such as bar in the above example).

Unloading code modules

(Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4)

Components.utils.unload() allows you to unload a previously imported code module. Once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference.

Examples

Extending resource: URLs

Prior to Gecko 2.0, the most common way to load code modules was using resource: URLs. The basic syntax of a resource URL is as follows:

resource://<alias>/<relative-path>/<file.js|jsm>

The <alias> is an alias to a location, usually a physical location relative to the application or XUL runtime. There are multiple pre-defined aliases set up by the XUL runtime:

  • app - Alias to the location of the XUL application
  • gre - Alias to the location of the XUL runtime

The <relative-path> can be multiple levels deep and is always relative to the location defined by the <alias>. The common relative path is "modules" and is used by XUL Runner and Firefox. Code modules are simple JavaScript files with a .js or .jsm extension.

<alias> must be unique to your add-on, as the application and other extensions share the same namespace for all aliases.

Using chrome.manifest

The easiest way for extensions and XUL applications to add custom aliases is by registering an alias in the chrome manifest using a line like this:

resource aliasname uri/to/files/

For example, if the XPI for your foo extension includes a top-level modules/directory containing the bar.js module (that is, the modules/directory is a sibling to chrome.manifest and install.rdf), you could create an alias to that directory via the instruction:

resource foo modules/

(Don't forget the trailing slash!) You could then import the module into your JavaScript code via the statement:

Components.utils.import("resource://foo/bar.js");

Programmatically adding aliases

Custom aliases to paths that can be represented as an nsILocalFile can be programmatically added as well. For example:

// Import Services.jsm unless in a scope where it's already been imported
Components.utils.import("resource://gre/modules/Services.jsm");

var resProt = Services.io.getProtocolHandler("resource")
                      .QueryInterface(Components.interfaces.nsIResProtocolHandler);

var aliasFile = Components.classes["@mozilla.org/file/local;1"]
                          .createInstance(Components.interfaces.nsILocalFile);
aliasFile.initWithPath("/some/absolute/path");

var aliasURI = Services.io.newFileURI(aliasFile);
resProt.setSubstitution("myalias", aliasURI);

// assuming the code modules are in the alias folder itself

Notes

Custom modules and XPCOM components

Note that prior to Gecko 2.0 JavaScript XPCOM components are loaded before chrome registration. This means you can't use Components.utils.import() with your own resource URL at the top level in a component source. A possible solution is moving the call to Components.utils.import() into the XPCOM component constructor (discussion).

Packaging notes

It's important to note that you should not typically put your JavaScript code modules in a JAR file in your add-on. Firefox 3.6 doesn't support them at all, and there's only one case in which it's remotely useful: a Firefox 4-only add-on which must be installed unpacked. Otherwise placing code modules in a JAR file breaks compatibility unnecessarily.

Importing CommonJS modules

The JavaScript code modules described here are not the same thing as CommonJS modules, but you can import CommonJS modules into any scope where you can use Components.utils.import. Just call the following:

const { require } = Cu.import("resource://gre/modules/commonjs/toolkit/require.js", {})

This will import require() into your scope.

You can then use that to import CommonJS modules. You can import Add-on SDK modules in just the same way you could from an SDK add-on:

// import the SDK's base64 module

var base64 = require("sdk/base64");
base64.encode("hello"); // "aGVsbG8="

You can import other CommonJS modules, too, as long as you know the path to them:

// import my module

var myModule = require("resource://path/to/my/module.js");

In this case, though, you might be better off creating your own loader, so you can specify the paths property yourself.

See also