• 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. Overlay extensions
  5. XUL School Tutorial
  6. Handling Preferences

Handling Preferences

In This Article
  1. Preferences in Firefox
  2. Adding preferences to an extension
  3. Managing preferences with XPCOM
      1. Preference listeners
  4. Preference windows

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.

« PreviousNext »

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.

« PreviousNext »

This tutorial was kindly donated to Mozilla by Appcoast.

Document Tags and Contributors

Tags: 
  • Add-ons
  • Extensions
  • XUL
  • XUL School
 Contributors to this page: wbamberg, Dao, Sheppy, teoli, Jorge.villalobos, DaveG
 Last updated by: wbamberg, Jul 4, 2016, 1:45:58 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