Настройка среды для разработки расширений

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

Эта статья дает предложения о том, как настроить приложение Mozilla для разработки расширений. Если не указано иное, эти предложения относятся к Firefox и Thunderbird, а также к SeaMonkey версии 2.0 и выше.

Обзор

  • Создать пользовательский профиль для разработчика, чтобы запустить сессию разработчика Firefox; со специальными настройками в about:config.
  • Установить несколько расширений для разработки Firefox в ваш профиль разработчика.
  • Отредактировать файлы в папке расширений вашего профиля и перезапустить приложение с профилем разработчика.

Профиль разработчика

Чтобы избежать снижения производительности из-за связанных с разработкой настроек и расширений, и, чтобы не потерять свои личные данные, вы можете использовать отдельный профиль для разработки.

Вы можете запустить два экземпляра Thunderbird или Firefox, в одно и то же время, используя отдельные профили и запускать приложения с параметрами -no-remote и -P ИмяПрофиля. Например, следующая команда запустит Firefox с профилем под названием "dev", независимо от того, запущен ли уже Firefox или нет. (Если еще нет никакого "dev" пользователя, то запустится экран выбора профиля, где вы сможете его создать.)

На Ubuntu (и многих других дистрибутивах Linux):

/usr/bin/firefox -no-remote -P dev

На некоторых других дистрибутивах Linux/Unix:

/usr/local/bin/firefox -no-remote -P dev

На Mac OS Snow Leopard (10.6) и новее:

/Applications/Firefox.app/Contents/MacOS/firefox-bin -no-remote -P dev &

На Mac OS Leopard (10.5) и старее, вам понадобится запросить 32-bit часть Universal Binary (https://bugzilla.mozilla.org/show_bug.cgi?id=622970):

arch -arch i386 /Applications/Firefox.app/Contents/MacOS/firefox-bin -no-remote -P dev &

На Windows:

Start -> Run "%ProgramFiles%\Mozilla Firefox\firefox.exe" -no-remote -P dev

На Windows 64 bit:

Start -> Run "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" -no-remote -P dev

Чтобы запустить Thunderbird или SeaMonkey вместо Firefox, замените "firefox" в примерах выше на "thunderbird" или "seamonkey".

Обратите внимание, что вы можете запустить Firefox с помощью обычного профиля при разработке.

Параметр -P ИмяПрофиля не включает -no-remote, поэтому используйте их вместе. В противном случае, если вы уже запустили экземпляр Firefox без -no-remote и попытаетесь запустить еще один экземпляр с -P ИмяПрофиля, но опять без -no-remote, то во втором вызове будет игнорироваться его параметр -P ИмяПрофиля, но вместо этого он откроет новое пустое окно для уже запущенного экземпляра (с общим профилем, сеансом и т.д.).

(Существует тред на Mozillazine форумах, где объясняют, как использовать стабильную и для разработки версии Firefox, чтобы проверить совместимость расширений. См. Установка Firefox 3 или Minefield, сохраняя Firefox 2.)

Командные флаги разработчика

As of Gecko 2 (Firefox 4), JavaScript files are cached ("fastload"). The -purgecaches command-line flag disables this behavior. Alternatively, you can set the MOZ_PURGE_CACHES environment variable. See this bug for more information.

Development preferences

Installing the Developer Profile extension sets up the development environment described below.

There is a set of development preferences that, when enabled, allows you to view more information about application activity, thus making debugging easier. However,  these preferences can degrade performance, so you may want to use a separate development profile when you enable these preferences. For more information about Mozilla preferences, refer to the mozillaZine article on "about:config".

Not all preferences are defined by default, and are therefore not listed in about:config by default. You will have to create new (boolean) entries for them.

  • javascript.options.showInConsole = true. Logs errors in chrome files to the Error Console.
  • nglayout.debug.disable_xul_cache = true. Disables the XUL cache so that changes to windows and dialogs do not require a restart. This assumes you're using directories rather than JARs. Changes to XUL overlays will still require reloading of the document overlaid.
  • browser.dom.window.dump.enabled = true. Enables the use of the dump() statement to print to the standard console. See window.dump for more info. You can use nsIConsoleService instead of dump() from a privileged script.
  • javascript.options.strict = true. Enables strict JavaScript warnings in the Error Console. Note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. You can filter those with Console2.
  • devtools.chrome.enabled = true. This enables to run JavaScript code snippets in the chrome context of the Scratchpad from the Tools menu. Don't forget to switch from content to browser as context.
  • extensions.logging.enabled = true. This will send more detailed information about installation and update problems to the Error Console. (Note that the extension manager automatically restarts the application at startup sometimes, which may mean you won't have time to see the messages logged before the automatic restart happens. To see them, prevent the automatic restart by setting the environment NO_EM_RESTART to 1 before starting the application.)
  • nglayout.debug.disable_xul_fastload = true. For Gecko 2.0+ (Firefox 4.0+). See this bug for more information. Although the bug has been closed, it is believed that this pref is still relevant.
  • You might also want to set dom.report_all_js_exceptions = true. See Exception logging in JavaScript for details.
  • devtools.errorconsole.deprecation_warnings. Detect deprecated code use.

Предупреждение: Never set nglayout.debug.disable_xul_fastload to true in a production environment; it exists solely to aid in debugging. In particular, add-ons should never change this preference.
.

Gecko 2.0 note
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

The Error Console is disabled by default starting in Firefox 4. You can re-enable it by changing the devtools.errorconsole.enabled preference to true and restarting the browser. With this, javascript.options.showInConsole is also set to true by default.

Accessing Firefox development preferences

To change preference settings in Firefox or SeaMonkey, type about:config in the Location Bar. Alternatively, use the Extension Developer's Extension, which provides a menu interface for Firefox settings.

Accessing Thunderbird development preferences

To change preference settings in Thunderbird, open the "Preferences" (Unix) or "Options" (Windows) interface. On the "Advanced" page, select the "General" tab then click the "Config Editor" button.

Development extensions

These extensions may help you with your development.

Firefox extension proxy file

Extension files are normally installed in the user profile. However, it is usually easier to place extension files in a temporary location, which also protects source files from accidental deletion. This section explains how to create a proxy file that points to an extension that is installed in a location other than the user profile.

  1. Get the extension ID from the extension's install.rdf file.
  2. Create a file in the "extensions" directory under your profile directory with the extension's ID as the file name (for example "your_profile_directory/extensions/{46D1B3C0-DB7A-4b1a-863A-6EE6F77ECB58}"). (How to find your profile directory) Alternatively, rather than using a GUID, create a unique ID using the format "name@yourdomain" (for example chromebug@mydomain.com) - then the proxy filename will be same as that ID, with no curly brackets {}.
  3. The contents of this file should be the path to the directory that contains your install.rdf file, for example /full/path/to/yourExtension/ on Mac and Linux, and C:\full\path\to\yourExtension\ on Windows. Remember to include the closing slash and remove any trailing whitespace.

    • Note: If you already installed the extension via XPI, you should uninstall it first before creating the pointer file.
    • Also note that the use of proxy files requires that the extension's chrome.manifest defines its chrome urls using traditional directories, rather than a JARed structure. See below.
  4. Place the file in the extensions folder of your profile and restart the application.

Using directories rather than JARs

Regardless of whether you choose to eventually package your extension's chrome in a JAR or in directories, developing in directories is simpler. If you choose a JARed structure for releasing, you can still develop with a directory structure by editing your chrome.manifest. For example, rather than having

content	myExtension	jar:chrome/myExtension.jar!/content/

use

content	myExtension	chrome/content/

Preventing the first launch extension selector

(Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5)

Starting in Firefox 8, on the first launch of a new version of Firefox, it presents user interface letting users select which third party add-ons to keep. This lets them weed out add-ons that were installed without their knowledge, or that are no longer needed.

However, this interface can be disruptive when debugging add-ons. You can avoid this by setting the preference extensions.autoDisableScopes to 14.

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

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