расширения загрузки

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Заметка: все расширения созданные с использованием  Add-on SDK являются загрузочными! Весь загрузочный код создается для вас, даже если вы и не думаете о нем. Не используется Add-on SDK? Читайте на...

Традиционные расширения включая overlays, когда в приложение может загрузится XUL из пакета расширения и автоматически применяются в их собственном UI (интерфейсе пользователя). Пока созданные расширения добавляются к UI приложения относительно легко, это означает что обновление, установка или отмена действия расширения запрашивается при перезагрузке приложения.

Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Расширение загрузки - введение. Это специальные расширения, которые вместо использования наложения, сами програмно добавляют свой интерфейс пользователя в приложение. Это делается запуском специального скрипт файла, который включается в расширение и содержит функции вызова браузера с командами для расширения - установить, удалить, загрузить, выгрузить.

Приложение запускающее такой скриптовый файл - расширение ответственное за добавление и удаление своего интерфейса пользователя и обработку любых других установок и выгрузок(остановок выполнений) задач ими пользующихся.

Эта статья поясняет как работают расширения загрузки. Смотри это руководство на преобразование приложения наложения в приложение загрузки для получения пошагового руководства по переходу.

The startup and shutdown process

A key feature of bootstrapped extensions is that they must be able to start up and shut down on demand by the application. When the extension's startup() function is called, it must manually inject its user interface and other behavior into the application. Similarly, when its shutdown() function is called, it must remove anything that it has added to the application, as well as all references to any of its objects.

There are several scenarios in which the startup() function may be called; for example:

  • When the extension is first installed, assuming that it's both compatible with the application and is enabled.
  • When the extension becomes enabled using the add-ons manager window.
  • When the application is started up, if the extension is enabled and compatible with the application.

Some examples of when the shutdown() function may be called:

  • When the extension is uninstalled, if it's currently enabled.
  • When the extension becomes disabled.
  • When the user quits the application, if the extension is enabled.

Notes on modifying the application user interface

chrome.manifest in bootstrapped add-ons

You can use a chrome.manifest file in bootstrapped add-ons to:

  • Make your add-on's content available via a chrome:// URL (using the content, locale, and skin instructions in the manifest).
  • Replace existing chrome:// URIs with your content (using the override instruction).

Not all chrome.manifest instructions are supported in bootstrapped add-ons, for example you still cannot register XUL Overlays from a bootstrapped add-on. See the chrome.manifest documentation for details.

In Firefox 10 and later the chrome.manifest file located in the root of the add-on's XPI (i.e. a sibling of the install.rdf) is loaded automatically. In Firefox 8 and 9 you had to load/unload the manifest manually using nsIComponentManager.addBootstrappedManifestLocation() and nsIComponentManager.removeBootstrappedManifestLocation(). This feature was unavailable in Firefox versions before 8.

Adding user interface manually

If you decide to go ahead and try to develop a bootstrapped extension that modifies the application's user interface, here are a few suggestions to get you started.

You need to look up the relevant application UI elements by their ID by calling document.getElementById(), then manipulate them to inject your UI. For example, you can get access to the menu bar in Firefox with document.getElementById("main-menubar").

Be sure that at shutdown time, you remove any user interface you've added.

Creating a bootstrapped extension

To mark an extension as bootstrappable, you need to add the following element to its install manifest:


Then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package.

Backward compatibility

Because older versions of Firefox don't know about the bootstrap property or bootstrap.js file, it's not overly difficult to create an XPI that will work on both as a bootstrappable extension and as a traditional extension. Create your extension as a bootstrappable extension, then add the traditional overlays as well. Newer versions of Firefox will use the bootstrap.js script, ignoring the components and overlays, while older versions will use the overlays.

Bootstrap entry points

The bootstrap.js script should contain several specific functions, which are called by the browser to manage the extension. The script gets executed in a privileged sandbox, which is cached until the extension is shut down.


Called when the extension needs to start itself up. This happens at application launch time, when the extension is enabled after being disabled or after it has been shut down in order to install an update. As such, this can be called many times during the lifetime of the application.

This is when your add-on should inject its UI, start up any tasks it may need running and so forth.

void startup(
A bootstrap data structure.
One of the reason constants, indicating why the extension is being started up. This will be one of APP_STARTUP, ADDON_ENABLE, ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.


Called when the extension needs to shut itself down, such as when the application is quitting or when the extension is about to be upgraded or disabled. Any user interface that has been injected must be removed, tasks shut down, and objects disposed of.

void shutdown(
A bootstrap data structure.
One of the reason constants, indicating why the extension is being shut down. This will be one of APP_SHUTDOWN, ADDON_DISABLE, ADDON_UNINSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.


Your bootstrap script must include an install() function, which the application calls before the first call to startup() after the extension is installed, upgraded, or downgraded.

Note: This method is never called if the extension has never been started. For example, if an extension is installed but isn't compatible with the current version of the application, install() will not get called. However, if the extension gets upgraded to a version that's compatible with the application, the install() function will be called at that time, before the first startup() call.
void install(
A bootstrap data structure.
One of the reason constants, indicating why the extension is being installed. This will be one of ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.


This function is called after the last call to shutdown() before a particular version of an extension is uninstalled. This will not be called if install() was never called.

Note: It's important to keep in mind that uninstall() can be called even on extensions that are currently disabled, or are not compatible with the current application. Because of this, it's crucial that the function be implemented to gracefully handle APIs that may not be present in the application. This function will also not be called if a third-party application removes the extension while Firefox isn't running.
Note: Simply having function install() {} IS NOT ENOUGH because if you have code in uninstall it will not run. You MUST run some code in the install function; at the least you must set parameters for the install function, such as: function install(aData, aReason) {}; then uninstall WILL WORK.
Note: If you open the add-on manager and then click "Remove" on an add-on, it will not call uninstall function right away. This is a soft uninstall because of the available "Undo" option. If the add-on manager is closed or another event takes place such that the "Undo" option becomes unavailable, then the hard uninstall takes place and the uninstall function is called.
Note: The uninstall function fires on downgrade and upgrade as well so you should make sure it is an uninstall by doing this:
function uninstall(aData, aReason) {
     if (aReason == ADDON_UNINSTALL) {
          console.log('really uninstalling');
     } else {
          console.log('not a permanent uninstall, likely an upgrade or downgrade');
void uninstall(
A bootstrap data structure.
One of the reason constants, indicating why the extension is being uninstalled. This will be one of ADDON_UNINSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.

Reason constants

The bootstrap functions accept a reason parameter, which explains to the extension why it's being called. The reason constants are:

Constant Value Description
APP_STARTUP 1 The application is starting up.
APP_SHUTDOWN 2 The application is shutting down.
ADDON_ENABLE 3 The add-on is being enabled.
ADDON_DISABLE 4 The add-on is being disabled. (Also sent during uninstallation)
ADDON_INSTALL 5 The add-on is being installed.
ADDON_UNINSTALL 6 The add-on is being uninstalled.
ADDON_UPGRADE 7 The add-on is being upgraded.
ADDON_DOWNGRADE 8 The add-on is being downgraded.

Bootstrap data

Each of the entry points is passed a simple data structure containing some useful information about the add-on being bootstrapped. More information about the add-on can be obtained by calling AddonManager.getAddonByID(). The data is a simple JavaScript object with the following properties:

Property Type Description
id string The ID of the add-on being bootstrapped.
version string The version of the add-on being bootstrapped.
installPath nsIFile The installation location of the add-on being bootstrapped. This may be a directory or an XPI file depending on whether the add-on is installed unpacked or not.
resourceURI nsIURI A URI pointing at the root of the add-ons files, this may be a jar: or file: URI depending on whether the add-on is installed unpacked or not.
oldVersion string The previously installed version, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is install or startup.
newVersion string The version to be installed, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is shutdown or uninstall.

Note: An add-on may be upgraded/downgraded at application startup, in this case the startup method reason is APP_STARTUP, and the oldVersion property is not set. Also be aware that in some circumstances an add-on upgrade/downgrade may occur without the uninstall method being called.

Add-on debugger

From Firefox 31 onwards, you can use the Add-on Debugger to debug bootstrapped add-ons.

Localization (L10n)

Localizing bootstrapped add-ons is very much the same since Firefox 7, as that is when chrome.manifest compatibility landed.

JS and JSM Files - Using Property Files

To localize your .js and .jsm files you have to use property files.

The absolute minimum needed here is:

  1. File: install.rdf
  2. File: chrome.manifest
  3. File: bootstrap.js
  4. Folder: locale
    1. Folder: VALID_LOCALE_HERE
      1. File: ANYTHING.properties

In the locale folder you must have folders for each of the languages you want to provide; each folder must be named a valid locale (ex: en-US). Inside this folder must be a property file. Inside the chrome.manifest file these locale must be defined. For example if you had a subfolder of en-US in locale folder your chrome.manifest file will have to contain: locale NAME_OF_YOUR_ADDON en-US locale/en-US/

Here is an example: GitHub :: l10n-properties - on startup of this add-on it will show a prompt saying USA or Great Britain, which ever it deems closest to your locale. You can test different locale by going to about:config and changing preference of general.useragent.locale to en-US and then to en-GB and disabling then re-enabling the add-on.

XUL and HTML Files - Using Entities from DTD Files

Many times HTML pages are used, however they cannot be localized with DTD files. There are three changes you must make:

  1. You have to change the HTML file's extension to be .xhtml
  2. The doctype must be defined point to a DTD file in your locale folder such as: <!DOCTYPE html SYSTEM "chrome://l10n/locale/mozilla.dtd">
  3. Must add xmlns attribute to html tag for example: <html xmlns="http://www.w3.org/1999/xhtml">

The bare minimum needed is:

  1. File: install.rdf
  2. File: chrome.manifest
  3. File: bootstrap.js
  4. Folder: locale
    1. Folder: VALID_LOCALE_HERE
      1. File: ANYTHING.dtd

The chrome.manifest file must include a definition for content for example: content NAME_OF_YOUR_ADDON ./

The chrome.manifest file must also include a line pointing to the locale, just like in the above property section, if you had a folder named en-US in locale, the chrome.manifest file should contain: locale NAME_OF_YOUR_ADDON en-US locale/en-US/

Here is an example add-on that opens an HTML page and a XUL page on install: GitHub :: l10n-xhtml-xul. Here is an example showing how to use a localized HTML page as an options page: GitHub :: l10n-html-options. You can go to about:config and change the value of the preference general.useragent.locale to en-US and then to en-GB and then reload the open pages to see the localization change.

Further reading

Метки документа и участники

 Внесли вклад в эту страницу: vlad_b
 Обновлялась последний раз: vlad_b,