• 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
Archive of obsolete content
  1. MDN
  2. Archive of obsolete content
  3. Adding preferences to an extension

Adding preferences to an extension

In This Article
  1. Download the sample
  2. Update the manifests
    1. Establish the defaults
  3. The JavaScript code
    1. startup()
    2. shutdown()
    3. observe()
    4. watchStock()
    5. refreshInformation()
    6. Installing the event listeners
  4. Design the preference dialog
  5. Alternative method: Inline Options
  6. Adding the context menu
  7. Examples
  8. See also

« PreviousNext »

This article takes the Creating a dynamic status bar extension sample to the next level, adding a popup menu that lets you quickly switch between multiple stocks to watch. It also adds a preference dialog that lets you switch to a stock other than one of the ones included in the popup menu.

As before, concepts covered in the previous articles in this series won't be rehashed here, so if you haven't already seen them:

  • Creating a status bar extension
  • Creating a dynamic status bar extension

Also, for reference, you may want to take a look at Preferences System and the Preferences API.

Download the sample

You can download a copy of this sample to look over, or to use as the basis for your own extension.
Get the code here: Download the sample

Update the manifests

The install manifest and chrome manifest need to be updated. By and large, the changes are simply changing the ID of the extension. However, we do need to add one new line to the install.rdf file:

 <em:optionsURL>chrome://stockwatcher2/content/options.xul</em:optionsURL>

This line establishes the URL of the XUL file that describes the options dialog.

Please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the Preferences button for your extension in the Add-ons list.

Establish the defaults

In order to set a default preference for the stock to monitor, we need to add a new folder to our extension's package, called "defaults", which in turn contains another folder called "preferences". Inside that, we create a file, defaults.js, that describes the default value of our preferences:

 pref("extensions.stockwatcher2.symbol", "GOOG");

The standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above.

The JavaScript code

In order to monitor changes to our preferences, we need to install an observer using the nsIPrefBranch2 interface. To do that, we need to reimplement our code into an object.

That involves turning each function into a member of the StockWatcher class. Let's take a look at each function in the class.

startup()

The StockWatcher.startup() function is called when our extension is first loaded. Its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information periodically.

var StockWatcher = {
   prefs: null,
   tickerSymbol: "",
   // Initialize the extension
   startup: function()
   {
     // Register to receive notifications of preference changes
     this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
         .getService(Components.interfaces.nsIPrefService)
         .getBranch("extensions.stockwatcher2.");
     this.prefs.addObserver("", this, false);
     this.tickerSymbol = this.prefs.getCharPref("symbol").toUpperCase();
     this.refreshInformation();    
     window.setInterval(this.refreshInformation, 10*60*1000); 
   }
 },

Our object has two member variables. prefs is configured by startup() to reference our extension's preferences, while tickerSymbol indicates the stock symbol to monitor.

The first thing the startup() function does is to get a reference to the preferences for our extension. This is done in two steps:

  • First, we get the Preferences service. This component handles preference management for Firefox and any extensions.
  • Second, we call nsIPrefService.getBranch(). This lets us specify a specific branch of the preference tree to access. By default, we would have access to all preferences, but we only want access to those belonging to our own extension, so we specify that we want to access the "extensions.stockwatcher2" branch.

After getting the preference branch for our extension, we call the nsISupports.QueryInterface() method on it to be able to use the methods of the nsIPrefBranch2 interface.

The next step is to register a preference observer by calling the addObserver() method to establish that whenever any events occur on the preferences, our object (this) receives notification. When events occur, such as a preference being altered, our observe() method will be called automatically.

Now that we're monitoring the preferences, we can set up to watch the stock information and display it in the status bar panel.

The first thing we need to do is get the currently configured stock symbol to watch from the preferences. To do so, we call the nsIPrefBranch.getCharPref() method, specifying that we want the preference named "symbol", which is where we store the user's selection for the stock to watch. We forcibly convert the symbol to upper-case since that's the way stock symbols are normally displayed.

Next, we call our own refreshInformation() method to immediately fetch and display the current information about the stock the extension is configured to monitor. We'll look at the details of how this method works later.

The last thing the startup() method does is to call the window.setInterval() DOM method to set up a callback that will automatically run our refreshInformation() method every 10 minutes. The interval time is specified in milliseconds.

shutdown()

The StockWatcher.shutdown() method deactivates the observer on the preferences. This is also where we would add any other shutdown tasks we need to perform.

shutdown: function() {
    this.prefs.removeObserver("", this);
},

observe()

The StockWatcher.observe() function is called whenever an event occurs on the preference branch we're watching. For details on how observers work, read up on the nsIObserver interface.

observe: function(subject, topic, data) {
     if (topic != "nsPref:changed")
     {
       return;
     }
     switch(data)
     {
       case "symbol":
         this.tickerSymbol = this.prefs.getCharPref("symbol").toUpperCase();
         this.refreshInformation();
         break;
     }
},

The topic parameter indicates what type of event occurred. If it's not nsPref:changed, we simply ignore the event, since all we're interested in is changes to the values of our preferences.

Once we've established that the event is in fact a preference change, we look at the data parameter, which contains the name of the preference that changed. In our example, we only have one preference, but you can monitor as many preferences as you wish here.

If the changed preference is "symbol", we grab the updated value of the preference by calling the nsIPrefBranch.getCharPref() method, and stash it in our tickerSymbol variable.

Once we've gotten the updated preference, we call refreshInformation() to immediately update the display with the new stock's information.

watchStock()

While we're at it, let's add a method that sets which stock we want to be watching, changing the preference and immediately requesting a refresh of the display. This method will be used when the user uses the popup menu we'll be adding to change what stock they're watching.

watchStock: function(newSymbol) {
     this.prefs.setCharPref("symbol", newSymbol);
},

The only new information for us here is the call to the preference object's setCharPref() function, which sets the value of the "symbol" preference.

Note that this call results in our StockWatcher.observe() method being invoked and displayed stock information being updated.

refreshInformation()

This method is slightly revised from previous versions, in that it needs to fetch the preference for the stock to watch and use that to construct the URL to monitor, as well as to construct the string to be displayed in the status bar panel.

refreshInformation: function() {
     // Because we may be called as a callback, we can't rely on
     // "this" referring to the right object, so we need to reference 
     // it by its full name
     var symbol = StockWatcher.tickerSymbol;
     var fullUrl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s="
         + symbol;
     function infoReceived() {
       var samplePanel = document.getElementById('stockwatcher2');
       var output = httpRequest.responseText;
       if (output.length) {
         // Remove any whitespace from the end of the string
         output = output.replace(/\W*$/, "");
         // Build the tooltip string
         var fieldArray = output.split(",");
         samplePanel.label = symbol + ": " + fieldArray[1];
         samplePanel.tooltipText = "Chg: " + fieldArray[4] + " | " +
             "Open: " + fieldArray[5] + " | " +
             "Low: " + fieldArray[6] + " | " +
             "High: " + fieldArray[7] + " | " +
             "Vol: " + fieldArray[8];
       }
     }
     var httpRequest = new XMLHttpRequest();
     httpRequest.open("GET", fullUrl, true);
     httpRequest.onload = infoReceived;
     httpRequest.send(null);
   }
}

Note that we use StockWatcher.tickerSymbol here instead of this.tickerSymbol to get the stock symbol to watch. We do this because since refreshInformation() is usually called as a callback from setInterval. In such cases this doesn't refer to the right object. See Method binding for detailed explanation.

Once we have the symbol in the local variable symbol, we use that to construct the URL and the string to display in the status bar panel.

Installing the event listeners

The only thing left to do is to install the event listeners needed to run the startup() and shutdown() routines automatically when the browser window is loaded and unloaded.

window.addEventListener("load", function(e) { StockWatcher.startup(); }, false);
window.addEventListener("unload", function(e) { StockWatcher.shutdown(); }, false);

Design the preference dialog

Now that we've written all the code, we need to build the XUL file for the options dialog.

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<prefwindow id="stockwatcher2-prefs"
     title="StockWatcher 2 Options"
     xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<prefpane id="sw2-stock-pane" label="Stock Settings">
  <preferences>
    <preference id="pref_symbol" name="extensions.stockwatcher2.symbol" type="string"/>
  </preferences>
  <hbox align="center">
    <label control="symbol" value="Stock to watch: "/>
    <textbox preference="pref_symbol" id="symbol" maxlength="4"/>
  </hbox>
</prefpane>
</prefwindow>

The <preferences> block establishes all the settings we implement as well as their types. In our case, we have a single preference, the stock symbol to monitor. Preferences are identified by name; in this case, the name is "extensions.stockwatcher2.symbol".

The actual user interface is described in the <prefpane> block. The <hbox> element is used to lay out the user interface by indicating that the widgets inside it should be positioned horizontally, next to each other in the window.

Our dialog has two widgets in it. The first is a label describing the textbox. The second is the textbox itself, in which the user enters the symbol. The preference property ties the textbox to the "pref_symbol" <preference> element and to the "extensions.stockwatcher2.symbol" preference. This lets the preference value automatically be updated to reflect the content of the textbox.

Alternative method: Inline Options

Requires Gecko 7(Firefox 7 / Thunderbird 7 / SeaMonkey 2.4)

You could use Inline Options for this preference.  You must set em:optionsType to 2 in your install.rdf. Your options.xul file would look like this:

<?xml version="1.0" ?>
<vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
  <setting pref="extensions.stockwatcher2.symbol" type="string" title="Stock to watch" />
</vbox>

Adding the context menu

Adding the contextual menu is easy; all the work that needs doing is done in the stockwatcher2.xul file. The first step is to add the context attribute to the status bar panel:

 <statusbar id="status-bar">
   <statusbarpanel id="stockwatcher2"
     label="Loading..."
     context="stockmenu"
     onclick="StockWatcher.refreshInformation()"
   />
 </statusbar>

Now when the user clicks on the status bar panel, the stock information refreshes, but when they right-click on it, a context menu pops up.

Defining the menu is also easy. All we need to do is add a popupset describing the menu to the statusbar, as follows:

 <popupset>
   <menupopup id="stockmenu">
     <menuitem label="Refresh Now" default="true"
               oncommand="StockWatcher.refreshInformation()"/>
     <menuseparator/>
     <menuitem label="Apple (AAPL)" oncommand="StockWatcher.watchStock('AAPL')"/>
     <menuitem label="Google (GOOG)" oncommand="StockWatcher.watchStock('GOOG')"/>
     <menuitem label="Microsoft (MSFT)" oncommand="StockWatcher.watchStock('MSFT')"/>
     <menuitem label="Yahoo! (YHOO)" oncommand="StockWatcher.watchStock('YHOO')"/>
   </menupopup>
 </popupset>

Each item in the menu has a label property, which specifies the text displayed in the menu, as well as an oncommand property, which indicates the JavaScript code to execute when the user selects that item.

The Refresh Now option calls the StockWatcher.refreshInformation() function, to refresh the display. The rest of the options call the StockWatcher.watchStock() function to start watching a different stock.

For a more detailed tutorial on creating popup menus, see XUL Tutorial:Popup Menus.

« PreviousNext »

override chrome://myaddon/content/options.xul chrome://myaddon/content/oldOptions.xul application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} appversion<=6.*

Examples

  • GitHub - Gist :: _ff-addon-template-bootstrapPrefsSkeleton - This Gist here is a fully working example of a fully funcitonal preferences skeleton, it uses the observer example from above. This example also uses a technique to trigger an onChange function that can be defined per preference and has the old value and along with the new value of the preference. It also uses a technique so you can just do prefs.preferenceName.setval('blah') instead of having to branch.setCharPref etc.

See also

  • https://wiki.mozilla.org/Mobile/Fennec/Extensions/Options
  • Add-ons > Code snippets > Preferences
  • Inline options [en-US]

Document Tags and Contributors

Tags: 
  • Add-ons
  • Extensions
  • Preferences system
  • XUL
 Contributors to this page: wbamberg, stephaniehobson, Noitidart, Nmaier, Jo3y, Sheppy, trevorh, mattflaschen, kmaglione, syssgx, darktrojan, janekschwarz, Kray2, Dfltr, Mgjbot, Ptak82, Mossop, Nickolay, Dbabbitt, Andreas Wuest
 Last updated by: stephaniehobson, Oct 21, 2015, 10:34:20 AM

  1. .htaccess ( hypertext access )
  2. <input> archive
  3. Add-ons
    1. Add-ons
    2. Firefox addons developer guide
    3. Interaction between privileged and non-privileged pages
    4. Tabbed browser
    5. bookmarks.export()
    6. bookmarks.import()
  4. Adding preferences to an extension
  5. An Interview With Douglas Bowman of Wired News
  6. Apps
    1. Apps
    2. App Development API Reference
    3. Designing Open Web Apps
    4. Graphics and UX
    5. Open web app architecture
    6. Tools and frameworks
    7. Validating web apps with the App Validator
  7. Archived Mozilla and build documentation
    1. Archived Mozilla and build documentation
    2. ActiveX Control for Hosting Netscape Plug-ins in IE
    3. Archived SpiderMonkey docs
    4. Autodial for Windows NT
    5. Automated testing tips and tricks
    6. Automatic Mozilla Configurator
    7. Automatically Handle Failed Asserts in Debug Builds
    8. BlackConnect
    9. Blackwood
    10. Bonsai
    11. Bookmark Keywords
    12. Building TransforMiiX standalone
    13. Chromeless
    14. Creating a Firefox sidebar extension
    15. Creating a Microsummary
    16. Creating a Mozilla Extension
    17. Creating a Release Tag
    18. Creating a Skin for Firefox/Getting Started
    19. Creating a Skin for Mozilla
    20. Creating a Skin for SeaMonkey 2.x
    21. Creating a hybrid CD
    22. Creating regular expressions for a microsummary generator
    23. DTrace
    24. Dehydra
    25. Developing New Mozilla Features
    26. Devmo 1.0 Launch Roadmap
    27. Download Manager improvements in Firefox 3
    28. Download Manager preferences
    29. Drag and Drop
    30. Embedding FAQ
    31. Embedding Mozilla in a Java Application using JavaXPCOM
    32. Error Console
    33. Exception logging in JavaScript
    34. Existing Content
    35. Extension Frequently Asked Questions
    36. Fighting Junk Mail with Netscape 7.1
    37. Firefox Sync
    38. Force RTL
    39. GRE
    40. Gecko Coding Help Wanted
    41. HTTP Class Overview
    42. Hacking wiki
    43. Help Viewer
    44. Helper Apps (and a bit of Save As)
    45. Hidden prefs
    46. How to Write and Land Nanojit Patches
    47. Introducing the Audio API extension
    48. Java in Firefox Extensions
    49. JavaScript crypto
    50. Jetpack
    51. Litmus tests
    52. Makefile.mozextension.2
    53. Microsummary topics
    54. Migrate apps from Internet Explorer to Mozilla
    55. Monitoring downloads
    56. Mozilla Application Framework
    57. Mozilla Crypto FAQ
    58. Mozilla Modules and Module Ownership
    59. Mozprocess
    60. Mozprofile
    61. Mozrunner
    62. Nanojit
    63. New Skin Notes
    64. Persona
    65. Plug-n-Hack
    66. Plugin Architecture
    67. Porting NSPR to Unix Platforms
    68. Priority Content
    69. Prism
    70. Proxy UI
    71. Remote XUL
    72. SXSW 2007 presentations
    73. Space Manager Detailed Design
    74. Space Manager High Level Design
    75. Standalone XPCOM
    76. Stress testing
    77. Structure of an installable bundle
    78. Supporting private browsing mode
    79. Table Cellmap
    80. Table Cellmap - Border Collapse
    81. Table Layout Regression Tests
    82. Table Layout Strategy
    83. Tamarin
    84. The Download Manager schema
    85. The life of an HTML HTTP request
    86. The new nsString class implementation (1999)
    87. TraceVis
    88. Treehydra
    89. URIScheme
    90. URIs and URLs
    91. Using Monotone With Mozilla CVS
    92. Using SVK With Mozilla CVS
    93. Using addresses of stack variables with NSPR threads on win16
    94. Venkman
    95. Video presentations
    96. Why Embed Gecko
    97. XML in Mozilla
    98. XPInstall
    99. XPJS Components Proposal
    100. XRE
    101. XTech 2005 Presentations
    102. XTech 2006 Presentations
    103. XUL Explorer
    104. XULRunner
    105. ant script to assemble an extension
    106. calICalendarView
    107. calICalendarViewController
    108. calIFileType
    109. xbDesignMode.js
  8. Archived open Web documentation
    1. Archived open Web documentation
    2. Browser Detection and Cross Browser Support
    3. Browser Feature Detection
    4. Displaying notifications (deprecated)
    5. E4X
    6. E4X Tutorial
    7. LiveConnect
    8. MSX Emulator (jsMSX)
    9. Old Proxy API
    10. Properly Using CSS and JavaScript in XHTML Documents
    11. Reference
    12. Scope Cheatsheet
    13. Server-Side JavaScript
    14. Sharp variables in JavaScript
    15. Standards-Compliant Authoring Tools
    16. Using JavaScript Generators in Firefox
    17. Window.importDialog()
    18. Writing JavaScript for XHTML
    19. XForms
    20. background-size
    21. forEach
  9. B2G OS
    1. B2G OS
    2. Automated Testing of B2G OS
    3. B2G OS APIs
    4. B2G OS add-ons
    5. B2G OS architecture
    6. B2G OS build prerequisites
    7. B2G OS phone guide
    8. Building B2G OS
    9. Building and installing B2G OS
    10. Building the B2G OS Simulator
    11. Choosing how to run Gaia or B2G
    12. Customization with the .userconfig file
    13. Debugging on Firefox OS
    14. Developer Mode
    15. Developing Firefox OS
    16. Firefox OS Simulator
    17. Firefox OS apps
    18. Firefox OS board guide
    19. Firefox OS developer release notes
    20. Firefox OS security
    21. Firefox OS usage tips
    22. Gaia
    23. Installing B2G OS on a mobile device
    24. Introduction to Firefox OS
    25. Mulet
    26. Open web apps quickstart
    27. Pandaboard
    28. PasscodeHelper Internals
    29. Porting B2G OS
    30. Preparing for your first B2G build
    31. Resources
    32. Running tests on Firefox OS: A guide for developers
    33. The B2G OS platform
    34. Troubleshooting B2G OS
    35. Using the App Manager
    36. Using the B2G emulators
    37. Web Bluetooth API (Firefox OS)
    38. Web Telephony API
    39. Web applications
  10. Beginner tutorials
    1. Beginner tutorials
    2. Creating reusable content with CSS and XBL
    3. Underscores in class and ID Names
    4. XML data
    5. XUL user interfaces
  11. Case Sensitivity in class and id Names
  12. Creating a dynamic status bar extension
  13. Creating a status bar extension
  14. Gecko Compatibility Handbook
  15. Getting the page URL in NPAPI plugin
  16. Index
  17. Inner-browsing extending the browser navigation paradigm
  18. Install.js
  19. JXON
  20. List of Former Mozilla-Based Applications
  21. List of Mozilla-Based Applications
  22. Localizing an extension
  23. MDN
    1. MDN
    2. Content kits
  24. MDN "meta-documentation" archive
    1. MDN "meta-documentation" archive
    2. Article page layout guide
    3. Blog posts to integrate into documentation
    4. Current events
    5. Custom CSS classes for MDN
    6. Design Document
    7. DevEdge
    8. Developer documentation process
    9. Disambiguation
    10. Documentation Wishlist
    11. Documentation planning and tracking
    12. Editing MDN pages
    13. Examples
    14. Existing Content/DOM in Mozilla
    15. External Redirects
    16. Finding the right place to document bugs
    17. Getting started as a new MDN contributor
    18. Landing page layout guide
    19. MDN content on WebPlatform.org
    20. MDN page layout guide
    21. MDN subproject list
    22. Needs Redirect
    23. Page types
    24. RecRoom documentation plan
    25. Remove in-content iframes
    26. Team status board
    27. Trello
    28. Using the Mozilla Developer Center
    29. Welcome to the Mozilla Developer Network
    30. Writing chrome code documentation plan
    31. Writing content
  25. MMgc
  26. Makefile - .mk files
  27. Marketplace
    1. Marketplace
    2. API
    3. Monetization
    4. Options
    5. Publishing
  28. Mozilla release FAQ
  29. Newsgroup summaries
    1. Newsgroup summaries
    2. Format
    3. Mozilla.dev.apps.firefox-2006-09-29
    4. Mozilla.dev.apps.firefox-2006-10-06
    5. mozilla-dev-accessibility
    6. mozilla-dev-apps-calendar
    7. mozilla-dev-apps-firefox
    8. mozilla-dev-apps-thunderbird
    9. mozilla-dev-builds
    10. mozilla-dev-embedding
    11. mozilla-dev-extensions
    12. mozilla-dev-i18n
    13. mozilla-dev-l10n
    14. mozilla-dev-planning
    15. mozilla-dev-platform
    16. mozilla-dev-quality
    17. mozilla-dev-security
    18. mozilla-dev-tech-js-engine
    19. mozilla-dev-tech-layout
    20. mozilla-dev-tech-xpcom
    21. mozilla-dev-tech-xul
    22. mozilla.dev.apps.calendar
    23. mozilla.dev.tech.js-engine
  30. Obsolete: XPCOM-based scripting for NPAPI plugins
  31. Plugins
    1. Plugins
    2. Adobe Flash
    3. External resources for plugin creation
    4. Logging Multi-Process Plugins
    5. Monitoring plugins
    6. Multi-process plugin architecture
    7. NPAPI plugin developer guide
    8. NPAPI plugin reference
    9. Samples and Test Cases
    10. Shipping a plugin as a Toolkit bundle
    11. Supporting private browsing in plugins
    12. The First Install Problem
    13. Writing a plugin for Mac OS X
    14. XEmbed Extension for Mozilla Plugins
  32. SAX
  33. Security
    1. Security
    2. Digital Signatures
    3. Encryption and Decryption
    4. Introduction to Public-Key Cryptography
    5. Introduction to SSL
    6. NSPR Release Engineering Guide
    7. SSL and TLS
  34. Solaris 10 Build Prerequisites
  35. Sunbird Theme Tutorial
  36. Table Reflow Internals
  37. Tamarin Tracing Build Documentation
  38. The Basics of Web Services
  39. Themes
    1. Themes
    2. Building a Theme
    3. Common Firefox theme issues and solutions
    4. Creating a Skin for Firefox
    5. Making sure your theme works with RTL locales
    6. Theme changes in Firefox 2
    7. Theme changes in Firefox 3
    8. Theme changes in Firefox 3.5
    9. Theme changes in Firefox 4
  40. Updating an extension to support multiple Mozilla applications
  41. Using IO Timeout And Interrupt On NT
  42. Using SSH to connect to CVS
  43. Using workers in extensions
  44. WebVR
    1. WebVR
    2. WebVR environment setup
  45. XQuery
  46. XUL Booster
  47. XUL Parser in Python