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.

Manejo de preferencias

Imagen:traduccion-pendiente.png Esta página está traduciéndose a partir del artículo XUL_School/Handling_Preferences, razón por la cual puede haber algunos errores sintácticos o partes sin traducir. Puedes colaborar continuando con la traducción

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
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.

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.

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.

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 FUEL

FUEL is a JS library integrated into Firefox that was meant to facilitate extension development. It fell a little short of its goals, but it is useful for preference handling. Firefox-based applications like Flock include FUEL, and SeaMonkey includes a FUEL equivalent called SMILE since version 2.

We modified our JSM sample extension so that it uses a preference instead of an internal variable. The main difference in functionality is that after closing Firefox and reopening it, our extension remembers how many greetings have been displayed before. The original extension only kept track of the greetings shown in a browser session. This new version persists this number across sessions.

Since the only reason we used non-chrome code in the JSM sample extension was to store the message count in a single location, we can easily modify this new extension so that it uses chrome code exclusively. There's no need for JavaScript Code Modules or XPCOM anymore. We're making this point because using the FUEL library from chrome code is slightly different thant using it from non-chrome code. The difference lies in how to get the "root" Application object:

// chrome code.
Application.something

// non-chrome code.
let application =
  Cc["@mozilla.org/fuel/application;1"].getService(Ci.fuelIApplication);
application.something

In the chrome you have the global Application object ready to use, while in non-chrome code you need to get it as an XPCOM service. It is an XPCOM service, with the difference that it can be more easily accessed in the chrome.

FUEL only works in Firefox 3 and above.

The Application object has a prefs property of type PreferenceBranch. You can use it to manage preferences easily.

First, you get an object that represents your preference:

this._countPref =
  application.prefs.get("extensions.xulschoolhello.message.count");

Then you can get or set its value using the value property.

/**
 * Returns the current message count.
 * @return the current message count.
 */
get count() { return this._countPref.value; },

/**
 * Increments the message count by one.
 */
increment : function() {
  this._countPref.value++;
}

The prefs object also has methods that allow you to get and set preference values directly, but we prefer this approach.

Preference Listeners

Sometimes you'll want to be notified when a preference changes its value. For example, if we wanted to have a display of the message count somewhere in the browser, we should use a preference listener to keep it up to date. This way we know we have the right value even if the user changes it manually in about:config.

To do this in FUEL, add an event listener for the "change" event:

this._countPref.events.addListener("change", this);

The listener object should implement the EventListener interface. Similarly to observers, all you need to do is have a handleEvent method in a JS object. Or you can use an anonymous function that takes an EventItem object.

this._countPref.events.addListener("change", function(aEvent) { /* do stuff. */ });

Always remember to remove listeners when you don't need them anymore.

Managing Preferences with XPCOM

The preferences system is implemented with XPCOM. FUEL is only a wrapper that gives the XPCOM services a friendlier face, so using either is pretty much the same. Using XPCOM is a little more verbose, as usual.

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.

Etiquetas y colaboradores del documento

 Colaboradores en esta página: teoli, camilourd
 Última actualización por: teoli,