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

Handling Preferences

We are planning to deprecate the use, in Firefox, of the techniques described in this document.

Don't use these techniques to develop new add-ons. Use WebExtensions or the Add-on SDK instead.

If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions or the SDK instead.

Add-ons developed using these techniques might not work with multiprocess Firefox (e10s), which is already the default in Firefox Nightly and Firefox Developer Edition, and will soon be the default in Beta and Release versions of Firefox. We have documentation on making your add-ons multiprocess-compatible, but it will be more future-proof for you to migrate to WebExtensions or the Add-on SDK.

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

Preferences in Firefox

Mozilla applications are highly customizable. Preferences are used to store settings and information to change their default behavior. To open the preferences window in Firefox, select the following from the main menu:

  • On Windows, Tools > Options
  • On Mac, Firefox > Preferences
  • On Linux, Edit > Preferences
Note: Keep in mind the usage of the terms "Preferences" and "Options" in different platforms. If you need to refer to the term "preference" in any of your locale files, you must change the string depending on the operating system. Tip: you can use window.navigator.platform in your chrome code to figure out the operating system Firefox is running on. You can use the Hidden DOM Window in non-chrome code.

Firefox loads user preferences from a number of sources. Each source is a JS file that contains some special functions not available in regular code. The following files are used:

  • Default preferences: these are stored in the directory defaults/pref in the Firefox installation directory.
  • Current preferences: these are stored in the profile directory with the name prefs.js. This is where the user's settings are stored. This file is updated when preferences are modified by the user.
  • User preferences: the file user.js in the user's profile directory holds additional preferences the user has set. This file is never written to by Firefox, but you may wish to set preferences manually in this file to override other settings.
  • Lockfile settings: these preferences are stored in a file that usually has the name mozilla.cfg or netscape.cfg. The file may be located on a network. It is intended to be used by an administrator or ISP to set settings centrally. In addition, certain preferences may be locked such that users cannot change them. Locked preferences are disabled in the Preferences window.

Firefox exposes its most common high-level preferences through the Preferences window and other parts of its UI. In reality there are thousands of other preferences Firefox handles that are not readily available to the user. These are hidden because they are too advanced or obscure for regular users to manage, and because the Preferences window should be as easy to use as possible. To access all other preferences, enter "about:config" into the Location Bar. This XUL page lists all the preferences defined in the Firefox installation, allowing you to change them as you please. As the warning message states, you should be very careful when changing preferences. Incorrect values can make Firefox behave oddly or break altogether.

You can type on the "Filter" textbox to search for specific preferences. If you type the word "homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its name or value. Right-clicking on the list reveals several options that allow you to modify preference values and add new ones. Preferences with non-default values are highlighted in bold. All changes done in about:config are saved to the prefs.js file.

The list in about:config is not complete. Some Firefox preferences have no default value, so they are left out unless you add them manually. An extensive specification of Firefox preferences can be seen in this page. You don't need to know them by heart; if doing task X requires some preference, then it's better to look for an explanation on how to do X rather than diving into the preferences list and see if you can find the preference you need. MDC articles and other guides are usually good at specifying the preferences you'll need to use.

Adding preferences to an extension

Extensions can read and write Firefox preferences and, most importantly, create and manage their own. The Preferences System provides a simple, unified storage facility for name / value mappings. When your storage needs are more complicated than this, you'll need more advanced APIs that will be discussed in a section further ahead.

To add preferences to your extension you should first create a JS preferences file that describes the preferences and their default values, although setting defaults is not required. As mentioned earlier, a preference with no default value can be set later on.

Note: We recommend that you include all of your extension preferences in the JS defaults file. It makes it easier to compile a list of the preferences your extensions handle, and to document what they do.

The preferences file you need to create should be defaults/preferences/yourextensionname.js, under your extension root. The naming of the JS file is not compulsory, but it is the standard most extensions use.

Note: The purpose of the defaults directory is to hold non-code files your extension needs. In the past we have used this directory to store XSLT files for XML transformations and local storage template files (more on this later). It's the best place to put miscellaneous files your extension needs.

Download this sample Hello World using preferences. There are a couple of additions in the Makefiles, to include the preference file xulschoolhello.js. The contents of the file are fairly simple:

// Amount of messages shown to the user.
pref("extensions.xulschoolhello.message.count", 0);

This defines a preference we'll use to keep track of the amount of times we have displayed a greeting message to the user. Its default value is 0. You'll see this preference appear in about:config after installing the extension. Just type "xulschool" in the filter box to see your new preference.

Note: Always begin your preference names with "extensions", followed by some namespacing and finally the actual name of the preference. Name parts are normally separated by dots.

Now let's look at how we actually manage the preference values.

Managing preferences with XPCOM

We use the Preferences Service in order to get and set preference values:

this._prefService =
  Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
// ...
get count() {
  return this._prefService.getIntPref("extensions.xulschoolhello.message.count");
},
increment : function() {
  let currentCount =
    this._prefService.getIntPref("extensions.xulschoolhello.message.count");
  
  this._prefService.setIntPref("extensions.xulschoolhello.message.count", currentCount + 1);
}

One important thing to keep in mind is that the "get" methods of the service can throw an exception if the preference is not found. If you are going to use XPCOM, you should always set a default value to your preferences, or use a try / catch block to prevent unhandled errors.

Preference listeners

The XPCOM way to add a listener was mentioned in the XPCOM section when describing the QueryInterface method:

this._prefService.QueryInterface(Ci.nsIPrefBranch2);
this._prefService.addObserver(prefName, this, false);
this._prefService.QueryInterface(Ci.nsIPrefBranch);

All the QI'ing is necessary because the addObserver method is in a different interface, and other than for adding and removing observers, we use the nsIPrefBranch interface for everything related to preferences.

Then, create the observer method:

observe : function(aSubject, aTopic, aData) {
  if ("nsPref:changed" == aTopic) {
    let newValue = aSubject.getIntPref(aData);
    // do something.
  }
},

Always remember to remove the observer when you don't need it anymore:

this._prefService.QueryInterface(Ci.nsIPrefBranch2);
this._prefService.removeObserver(prefName, this);

Preference windows

It's very common for extensions to have a few settings that their users can change to tailor them to their needs. Since there are some subtleties related to preference management, there are some facilities provided in XUL and Firefox that make this much easier to deal with.

The standard way of opening a preferences window is to open the Add-ons Manager, select the add-on, and then click on the Preferences button. In order to have this button enabled in your extension you need to add the following line to install.rdf:

<em:optionsURL>chrome://xulschoolhello/content/preferencesWindow.xul</em:optionsURL>

If you want to open this window from a different place in the UI, such as a menu item or a button in a toolbar, you need to take into account that the opening behavior of a Preferences window is different depending on the operating system. This is how we do it:

openPreferences : function() {
  if (null == this._preferencesWindow || this._preferencesWindow.closed) {
    let instantApply =
      Application.prefs.get("browser.preferences.instantApply");
    let features =
      "chrome,titlebar,toolbar,centerscreen" +
      (instantApply.value ? ",dialog=no" : ",modal");

    this._preferencesWindow =
      window.openDialog(
        "chrome://xulschoolhello/content/preferencesWindow.xul",
        "xulschoolhello-preferences-window", features);
  }

  this._preferencesWindow.focus();
},

This code is based on the code that opens Preference windows from the Add-ons Manager. It does 2 things:

  1. Check if the Preferences window is already open. In that case, just give it focus.
  2. Make the window modal in systems where the instant apply rule is not used. Notice that this is a preference that users can switch, so checking for the operating system is not good enough.
The general philosophy in non-Windows systems is that a change in a preference applies immediately. Preference windows don't have any buttons, or just an OK or Close button. On Windows, changing preferences don't apply until the user click on the OK button. The user can click on the Cancel button and none of the changes performed in the window will apply. This is why it makes sense to have Preference windows be modal on Windows. This way the user is urged to apply or discard any changes instead of being able to ignore the Preferences window.

For preferences windows you should always use the prefwindow element instead of window in your XUL file. Firefox will know if it needs to add OK and Cancel buttons or not.

In most cases, your preferences window will have a few options that can be displayed all at once. If you have many preferences, you can organize them using the prefpane element. This creates a visually appealing tabbed view, just like the one in the Firefox Preferences window. The prefpane is just a container, and you can have as many as you want. The tabs at the top of the window will need icons, and just like with toolbar buttons there are subtle differences between operating systems.

The prefwindow allows you to use the preferences and preference elements, which facilitate preference handling. The preferences element is just a container, and you should have one per window, or one per prefpane if you have those. The element and its children are completely invisible, and their purpose is to list the preferences to be used in the window/pane.

<preferences>
  <preference id="xulschoolhello-message-count-pref"
    name="extensions.xulschoolhello.message.count" type="int" />
  <!-- More preference elements. -->

</preferences>

After you define the preferences you need, you associate them with the form elements in your window or pane using the preference attribute:

<textbox preference="xulschoolhello-message-count-pref" type="number"
  min="0" max="100" />

In this case we use a numeric field to set the message count preference. Changing the value in the control will change the preference (depending on the instant apply rule), and vice versa. You may be able to create a Preferences window without a single line of JS code thanks to the preference element.

Finally, groupboxes are a good idea to organize the contents of the window and preference panes. They are heavily stylized in the Firefox Preferences window, so you should include the same CSS file that is included in it (chrome://browser/skin/preferences/preferences.css). This way you don't have to rewrite all the CSS rules defined for Firefox. You should also look at the class values set to elements in the XUL file, so that your Preferences window is just like the one in Firefox and your extension is better integrated into the application and the native OS look and feel.

This tutorial was kindly donated to Mozilla by Appcoast.

Document Tags and Contributors

 Contributors to this page: wbamberg, Dao, Sheppy, teoli, Jorge.villalobos, DaveG
 Last updated by: wbamberg,