jdmry
jdmry

Reputation: 53

Firefox extension include script in main.js file

I am writing an extension for firefox and having a problem including scripts into the main.js (background) file ...

In my case I would like to include for example jquery.js and config.js but I can't see how to do it properly.

In my chrome extension I just do that on the manifest file but I would like the equivalent in firefox.

Thank you for your help, jdmry

Upvotes: 3

Views: 2415

Answers (1)

Makyen
Makyen

Reputation: 33376

To import files you use Components.utils.import.

You will need a URL from which to import the file. Usually, this is either a resource:// or chrome:// URL.

Some examples of Mozilla supplied libraries:

Components.utils.import("resource://gre/modules/FileUtils.jsm"); //File Utilities
Components.utils.import("resource://gre/modules/NetUtil.jsm");   //Network utilities
Components.utils.import("resource://gre/modules/Services.jsm");  //Services

Some examples of loading from your own extension:

Components.utils.import("chrome://myExtensionModule/content/common.jsm");          //Common
Components.utils.import("chrome://myExtensionModule/content/classes.jsm");         //Classes

In order to load from your own extension, you will need to have the files in a folder that has been mapped to a chrome:// or resource:// URL within your chrome.manifest. For example with the line:

content       myExtensionModule                             modules/

This does not need to be separate from the folder which you normally map for content, but it is common to keep JavaScript modules in a separate folder, just for organization. You do not need to have them use a .jsm extension, again just a convention. Using .js is just fine and may be desirable if you have other tools which auto-config based on a .js extension (e.g. an editor).

Significantly more information can be found in the documentation on MDN:

Note that in Firefox code it is common for there to be a mapping to shorter variables to access some commonly used Firefox properties. Specifically, the following are often used:

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Usually these are defined in a much more abbreviated manner. They are explicitly stated above to make the mapping more clear.

Upvotes: 2

Related Questions