From a065e04d529da1d847b5062a12c46d916408bf32 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 21:46:22 -0500 Subject: update based on https://github.com/mdn/yari/issues/2028 --- .../mozilla/add-ons/add-on_guidelines/index.html | 121 ----- files/ru/mozilla/add-ons/amo/index.html | 11 - files/ru/mozilla/add-ons/amo/policy/index.html | 22 - files/ru/mozilla/add-ons/code_snippets/index.html | 148 ----- .../\320\272\321\203\320\272\320\270/index.html" | 36 -- .../mozilla/add-ons/firefox_for_android/index.html | 82 --- .../index.html | 395 -------------- .../mozilla/add-ons/overlay_extensions/index.html | 65 --- files/ru/mozilla/add-ons/sdk/guides/index.html | 365 ------------- .../index.html" | 519 ------------------ .../sdk/high-level_apis/addon-page/index.html | 32 -- .../sdk/high-level_apis/context-menu/index.html | 578 -------------------- .../mozilla/add-ons/sdk/high-level_apis/index.html | 10 - .../sdk/high-level_apis/passwords/index.html | 525 ------------------ files/ru/mozilla/add-ons/sdk/index.html | 90 ---- .../mozilla/add-ons/sdk/low-level_apis/index.html | 23 - .../sdk/low-level_apis/places_bookmarks/index.html | 595 --------------------- .../mozilla/add-ons/sdk/tools/console/index.html | 110 ---- files/ru/mozilla/add-ons/sdk/tools/index.html | 10 - files/ru/mozilla/add-ons/sdk/tools/jpm/index.html | 497 ----------------- .../sdk/tutorials/getting_started_(jpm)/index.html | 157 ------ files/ru/mozilla/add-ons/sdk/tutorials/index.html | 145 ----- .../add-ons/sdk/tutorials/installation/index.html | 68 --- .../creating_annotations/index.html" | 221 -------- .../implementing_the_widget/index.html" | 68 --- .../index.html" | 34 -- .../overview/index.html" | 34 -- .../index.html" | 94 ---- .../index.html" | 61 --- .../index.html" | 14 - .../index.html" | 353 ------------ .../index.html" | 102 ---- 32 files changed, 5585 deletions(-) delete mode 100644 files/ru/mozilla/add-ons/add-on_guidelines/index.html delete mode 100644 files/ru/mozilla/add-ons/amo/index.html delete mode 100644 files/ru/mozilla/add-ons/amo/policy/index.html delete mode 100644 files/ru/mozilla/add-ons/code_snippets/index.html delete mode 100644 "files/ru/mozilla/add-ons/code_snippets/\320\272\321\203\320\272\320\270/index.html" delete mode 100644 files/ru/mozilla/add-ons/firefox_for_android/index.html delete mode 100644 files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html delete mode 100644 files/ru/mozilla/add-ons/overlay_extensions/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/guides/index.html delete mode 100644 "files/ru/mozilla/add-ons/sdk/guides/\321\201\320\272\321\200\320\270\320\277\321\202\321\213_\321\201\320\276\320\264\320\265\321\200\320\266\320\270\320\274\320\276\320\263\320\276/index.html" delete mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/low-level_apis/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tools/console/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tools/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tools/jpm/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/index.html delete mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/creating_annotations/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/implementing_the_widget/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/overview/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\264\320\276\320\261\320\260\320\262\320\273\320\265\320\275\320\270\320\265_\320\272\320\275\320\276\320\277\320\272\320\270_\320\275\320\260_\320\277\320\260\320\275\320\265\320\273\321\214_\320\270\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\320\276\320\262/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/tutorials/\320\277\321\200\320\276\321\202\320\276\320\272\320\276\320\273\320\270\321\200\320\276\320\262\320\260\320\275\320\270\320\265/index.html" delete mode 100644 "files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" delete mode 100644 "files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" delete mode 100644 "files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" (limited to 'files/ru/mozilla/add-ons') diff --git a/files/ru/mozilla/add-ons/add-on_guidelines/index.html b/files/ru/mozilla/add-ons/add-on_guidelines/index.html deleted file mode 100644 index 5be041195c..0000000000 --- a/files/ru/mozilla/add-ons/add-on_guidelines/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Add-on guidelines -slug: Mozilla/Add-ons/Add-on_guidelines -translation_of: 'https://extensionworkshop.com/documentation/publish/add-on-policies/' ---- -

These add-on guidelines were created to foster an open and diverse add-on developer community while ensuring an excellent user experience. They apply to all add-ons and add-on updates regardless of where they are hosted, and also apply to customizations performed by installers that configure Firefox without using an add-on. Add-ons hosted on AMO are subject to additional policies.

- -

Be Transparent

- - - -

Be Respectful to Users

- - - -

Be Safe

- - - -

Be Stable

- - - -

Exceptions

- - - -

Other exceptions may apply.

- -

Enforcement

- -

Add-ons that do not follow these guidelines may qualify for blocklisting, depending on the extent of the violations. Guidelines qualified with the wordmust are especially important, and violations thereof will most likely result in a blocklisting nomination.

- -

The Add-ons Team will do their best to contact the add-on's developers and provide a reasonable time frame for the problems to be corrected before a block is put in place. If an add-on is considered malicious or its developers have proven unreachable or unresponsive, or in case of repeat violations, blocklisting may be immediate.

- -

Guideline violations should be reported via Bugzilla, under Tech Evangelism > Add-ons. Questions can be posted in the #addons IRC channel.

- -

These guidelines may change in the future. All updates will be announced in the Add-ons Blog.

diff --git a/files/ru/mozilla/add-ons/amo/index.html b/files/ru/mozilla/add-ons/amo/index.html deleted file mode 100644 index 0845e54e3d..0000000000 --- a/files/ru/mozilla/add-ons/amo/index.html +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: AMO -slug: Mozilla/Add-ons/AMO -tags: - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Add-ons/AMO ---- -

{{AddonSidebar}}

- -

Content to be added.

diff --git a/files/ru/mozilla/add-ons/amo/policy/index.html b/files/ru/mozilla/add-ons/amo/policy/index.html deleted file mode 100644 index 7baca9debb..0000000000 --- a/files/ru/mozilla/add-ons/amo/policy/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: AMO Policies -slug: Mozilla/Add-ons/AMO/Policy -tags: - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Add-ons/AMO/Policy ---- -

{{AddonSidebar}}

- -

Mozilla стремится обеспечить отличный опыт для наших пользователей и разработчиков надстроек. Перед отправкой своего дополнения ознакомьтесь с приведенными ниже правилами.

- - -
-
Пакт о разработке
-
Effective January 5, 2016
Обзор процесса
-
Add-ons extend the core capabilities of Firefox, allowing users to modify and personalize their Web experience. A healthy add-on ecosystem, built on trust, is vital for developers to be successful and users to feel safe making Firefox their own. For these reasons, Mozilla requires all add-ons to comply with the following set of policies on acceptable practices. The below is not intended to serve as legal advice, nor is it intended to serve as a comprehensive list of terms to include in your add-on’s privacy policy.
Избранные дополнения
-
How up-and-coming add-ons become featured and what's involved in the process.
Связаться с нами
-
Add-ons allow developers to extend and modify the functionality of Firefox.

- Связаться с нами
- Как связаться с нами в отношении этих политик или вашего дополнения. -
diff --git a/files/ru/mozilla/add-ons/code_snippets/index.html b/files/ru/mozilla/add-ons/code_snippets/index.html deleted file mode 100644 index d7e42cd381..0000000000 --- a/files/ru/mozilla/add-ons/code_snippets/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Code snippets -slug: Mozilla/Add-ons/Code_snippets -tags: - - Add-ons - - Code snippets - - Extensions - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Code_snippets ---- -

 

- -
-

Дополнения с использованием методов, описанных в этом документе, считаются устаревшей технологией в Firefox. Не используйте эти методы для разработки новых дополнений. Используйте вместо этого WebExtensions. Если вы поддерживаете надстройку, которая использует описанные здесь методы, рассмотрите возможность переноса ее на использование WebExtensions.

- -

Начиная с Firefox 53, никакие новые устаревшие дополнения не будут приниматься addons.mozilla.org (AMO) для Firefox на ПК и Firefox для Android.

- -

Начиная с Firefox 57, только дополнения разработанные на основе WebExtensions API будут поддерживаться для Firefox на ПК и Firefox для Android.

- -

 Даже до Firefox 57 изменения, появляющиеся на платформе Firefox, нарушат многие устаревшие расширения. Эти изменения включают многопроцессорные Firefox (e10s), песочницу и несколько процессов контента. Устаревшие расширения, на которые влияют эти изменения, должны мигрировать, чтобы использовать API WebExtensions, если они могут. Дополнительную информацию см. в документе "Признаки совместимости".

- -

Страница wiki, содержащая ресурсы, пути миграции, рабочие часы и т.д., доступна, чтобы помочь разработчикам перейти на новые технологии.

-
- -

 

- -

This is a quick list of useful code snippets (small code samples) available for developers of extensions for the various Mozilla applications. Many of these samples can also be used in XULRunner applications, as well as in actual Mozilla code itself.

- -

These examples demonstrate how to accomplish basic tasks that might not be immediately obvious.

- -

General

- -
-
Examples and demos from MDN articles
-
A collection of examples and demos from articles.
-
Window code
-
Opening and manipulating windows
-
Toolbar
-
Toolbar related code
-
Sidebar
-
Sidebar related code
-
Forms
-
Forms related code
-
XML
-
Code used to parse, write, manipulate, etc. XML
-
File I/O
-
Code used to read, write and process files
-
Drag & Drop
-
Code used to setup and handle drag and drop events
-
Dialogs
-
Code used to display and process dialog boxes
-
Alerts and Notifications
-
Modal and non-modal ways to notify users
-
Preferences
-
Code used to read, write, and modify preferences
-
JS XPCOM
-
Code used to define and call XPCOM components in JavaScript
-
Running applications
-
Code used to run other applications
-
<canvas> related
-
WHAT WG Canvas-related code
-
Signing a XPI
-
How to sign an XPI with PKI
-
Delayed Execution
-
Performing background operations.
-
Miscellaneous
-
Miscellaneous useful code fragments
-
HTML to DOM
-
Using a hidden browser element to parse HTML to a window's DOM
-
- -

JavaScript libraries

- -

Here are some JavaScript libraries that may come in handy.

- -
-
StringView
-
A library that implements a StringView view for JavaScript typed arrays. This lets you access data in typed arrays using C-like string functions.
-
Rosetta
-
By default, the only possible standardized scripting language for HTML is ECMAScript. Hence, if you are going to use another scripting language you might expect that most of the browsers will not recognize it. Nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ECMAScript allow us, in theory, to build full virtual machines in pure ECMAScript. Therefore, it is also possible, in theory, to use ECMAScript for a smaller task: parsing exotic programming languages (i.e., creating compilers). This snippets shows a possible way to start from.
-
- -

Browser-oriented code

- -
-
Tabbed browser code (Firefox/SeaMonkey)
-
Basic operations, such as page loading, with the tabbed browser, which is the heart of Mozilla's browser applications
-
Cookies
-
Reading, writing, modifying, and removing cookies
-
Page Loading
-
Code used to load pages, reload pages, and listen for page loads
-
Interaction between privileged and non-privileged code
-
How to communicate from extensions to websites and vice-versa.
-
Downloading Files
-
Code to download files, images, and to monitor download progress
-
Password Manager
-
Code used to read and write passwords to/from the integrated password manager
-
Bookmarks
-
Code used to read and write bookmarks
-
JavaScript Debugger Service
-
Code used to interact with the JavaScript Debugger Service
-
- -

SVG

- -
-
General
-
General information and utilities
-
SVG Animation
-
Animate SVG using JavaScript and SMIL
-
SVG Interacting with Script
-
Using JavaScript and DOM events to create interactive SVG
-
Embedding SVG in HTML and XUL
-
Using SVG to enhance HTML or XUL based markup
-
- -

XUL Widgets

- -
-
HTML in XUL for Rich Tooltips
-
Dynamically embed HTML into a XUL element to attain markup in a tooltip
-
Label and description
-
Special uses and line breaking examples
-
Tree
-
Setup and manipulation of trees using XUL and JS
-
Scrollbar
-
Changing style of scrollbars. Applies to scrollbars in browser and iframe as well.
-
Autocomplete
-
Code used to enable form autocomplete in a browser
-
Boxes
-
Tips and tricks when using boxes as containers
-
Tabbox
-
Removing and manipulating tabs in a tabbox
-
- -

Windows-specific

- -
-
Finding Window Handles (HWND) (Firefox)
-
How to use Windows API calls to find various kinds of Mozilla window handles. Window handles can be used for IPC and Accessibility purposes.
-
Using the Windows Registry with XPCOM
-
How to read, write, modify, delete, enumerate, and watch registry keys and values.
-
- - - -

The content at MozillaZine Example Code is slowly being moved here, but you can still find useful examples there for now.

diff --git "a/files/ru/mozilla/add-ons/code_snippets/\320\272\321\203\320\272\320\270/index.html" "b/files/ru/mozilla/add-ons/code_snippets/\320\272\321\203\320\272\320\270/index.html" deleted file mode 100644 index 7a77657bdb..0000000000 --- "a/files/ru/mozilla/add-ons/code_snippets/\320\272\321\203\320\272\320\270/index.html" +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Cookies -slug: Mozilla/Add-ons/Code_snippets/куки -translation_of: Archive/Add-ons/Code_snippets/Cookies ---- -

Чтение существующих cookie

- -

Cookie для данного хоста, как объекты nsICookie2, могут быть пронумерированны так:

- -
let enum = Services.cookies.getCookiesFromHost("example.com");
-while (enum.hasMoreElements()) {
-  var cookie = e.getNext().QueryInterface(Ci.nsICookie2);
-  dump(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n");
-}
-
- -

Все cookie, вне зависимости от хоста, могут быть пронумерированны с помощью Services.cookies.enumerator, а не getCookiesFromHost().

- - - -

Следующий код показывает как настроить cookie в Firefox.

- -
Services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date);
-
- -

Смотрите также

- - diff --git a/files/ru/mozilla/add-ons/firefox_for_android/index.html b/files/ru/mozilla/add-ons/firefox_for_android/index.html deleted file mode 100644 index a636438acb..0000000000 --- a/files/ru/mozilla/add-ons/firefox_for_android/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Устаревшие расширения для Firefox для Android -slug: Mozilla/Add-ons/Firefox_for_Android -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Legacy_Firefox_for_Android ---- -

Firefox для Android поддерживает надстройки, используя ту же систему расширения, что и все другие приложения на базе Gecko. Вы можете использовать SDK Add-on или создать вручную bootstrap-дополнения. Вы даже можете создавать традиционные перезагружаемые дополнения, хотя предпочтительны и другие два подхода.

- -

Дополнения, которые работают с настольным Firefox, не работают автоматически в Firefox для Android:

- - - -

Следующие статьи предоставляют помощь в разработке расширений для Firefox на Android. Кроме того, обратитесь к общей документации по расширениям, которая применяется ко всем приложениям Mozilla

- -
-
-

Учебники

- -
-
Прохождение
-
Разработка, упаковка и установка простого дополнения для Firefox для Android.
-
Прохождение Firefox Hub
-
Как разработать Firefox Hub add-on и добавить его в Firefox для Android (главная страница).
-
Add-on SDK
-
Как разрабатывать дополнения Firefox для Android с помощью Add-on SDK.
-
- -

Образец кода

- -
-
Фрагменты кода
-
Образцы кода для общих задач.
-
Инициализация и очистка
-
Как инициализировать ваше дополнение при его запуске и очистке при его закрытии.
-
Firefox для Android Add-ons в репозитории Github
-
Коллекция модулей JS, кода примера и плагинов-репозиториев, которые помогут вам создавать надстройки для Firefox для Android.
-
-
- -
-

Справка по API

- -
-
NativeWindow
-
Создайте собственные виджеты пользовательского интерфейса Android.
-
BrowserApp
-
Доступ к вкладкам браузера и веб-содержимому, которое они размещают.
-
Prompt.jsm
-
Вывод встроенного диалогового окна Android.
-
HelperApps.jsm
-
Запросить и запустить собственные приложения, установленные в системе.
-
Notifications.jsm
-
Использование внешних свойств уведомлений системы Android.
-
Home.jsm
-
Настройка домашней страницы.
-
HomeProvider.jsm
-
Сохранять данные для отображения на главной странице.
-
 
-
-
-
- -

 

- -
-
 
-
- -
-
 
-
- -
-
 
-
diff --git a/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html b/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html deleted file mode 100644 index ae42b11ad1..0000000000 --- a/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: How to convert an overlay extension to restartless -slug: Mozilla/Add-ons/How_to_convert_an_overlay_extension_to_restartless -translation_of: Archive/Add-ons/How_to_convert_an_overlay_extension_to_restartless ---- -
-

This article is a step-by-step tutorial on how to convert an old overlay-based extension into a restartless (bootstrapped) extension that is also extractionless.

-
- -

Requirements

- -

First off, what kind of add-on are we talking about here? Well, XUL overlays and windows, JSM files, chrome & resource mappings with localization, default preferences, but no XPCOM components of your own. Some of that will have to be replaced and the rest will need to be loaded differently.

- -

Next, what's the minimum version of Firefox we should require (preferably an ESR)? This guide targets Firefox 17 ESR or later (or anything else Gecko 17+, such as SeaMonkey 2.14+). This istwo ESRs back (as of this writing), which should be plenty. Using the current Firefox ESR, stable version, or Nightly is generally a better idea if given the option, but some users take forever to upgrade.

- -

There will be no usage of the Add-on SDK or any other external libraries here. Everything will use APIs available in Firefox 17+ or code provided here.

- -

Step 1: Use Services.jsm

- -

If you load one of Mozilla's internal JSM files, for example Services.jsm, you'll do so via privileged JavaScript code like this:

- -
Components.utils.import("resource://gre/modules/Services.jsm");
- -

From here on out, it is assumed you've imported Services.jsm somewhere at the top of whatever file you're in and will be using it in all code examples. The examples will also assume that you know how to properly add instructions to your add-on's chrome.manifest to add and remove resource, chrome, locale, & etc. mappings, so that you can access your files with custom paths such as:

- -
resource://myAddon/filename.ext
-chrome://myAddon/content/filename.ext
- -

Step 2: No more resource:// URIs for files internal to your bundle

- -

Unfortunately, resource mappings in your chrome.manifest are still not usable in restartless add-ons, which looks bad, but only because Mozilla is still using resource:// URIs internally and in examples. Resource mappings for files in the mozilla distribution, such as Services.jsm (above), will continue to work. In overlay extensions, you can place a resource mapping in the chrome.manifest for your add-on and load your own JSM from resource:// URIs. It's a great way to modularize your code that's been available since Firefox 3. You can use chrome:// URIs with "Components.utils.import()" just fine; in fact you've been able to since Firefox 4. However, because it was implemented first for only file:// and resource:// but not chrome://, everyone who learned of this new feature learned that you had to load JSM from resource:// URIs and just stuck with that forever. It does still work if you don't have restartlessness to worry about, though the protocol (or scheme, or whatever term you prefer) really should be avoided at this point. The resource:// protocol actually bleeds into content which allows webpages to detect installed add-ons using the protocol, which is not particularly fantastic (just the static file contents, not any loaded script/data).

- -

Step 2a: Load your JSM from chrome://

- -

Now with that preface out of the way, this part is easy: drop support for Firefox 3.x if you haven't already, move your JSM files to wherever you've got your chrome mapping to for your XUL overlay and/or windows, import your files from that new chrome mapped path instead of the old resource one, and remove your "resource" line from your chrome.manifest file. It's probably a good idea to do this even if you aren't going fully restartless / extractionless due to the previously mentioned exposure to content of resource mappings.

- -

Also, drop support for Firefox 4 through 9 while you're at it. Prior to Firefox 10, the chrome.manifest file you rely on wasn't loaded automatically for restartless add-ons. Hacks were required, and probably a bad idea.

- -

Step 2b: Audit any remaining resource:// URI usage internal to your extension

- -

If you don't need resource:// URIs for anything else, then you may be able to skip the next step. If not, see if you still can't do things any other way. As with JSMs, a chrome:// URI may be more appropriate. If you want to also make your add-on extractionless then you may need "step 3" if you're loading files with nsIFileInputStream or something similar, or a jar: URI might work. If not, a file:// URI might be fine for you. Restartless add-ons can easily get a URI for their install location on startup, so you should look into what you can do with that.

- -

Step 3: No more nsIFile access for files internal to your bundle

- -

For an extractionless extension, access to files internal to your bundle will not be possible using the nsIFile interface.

- -

If you need to read data, or otherwise access files within your bundle, there are two options. The first is to use the nsIZipReader interface which permits continuing to use nsIInputStreams, etc. The second is to re-code to use XMLHttpRequest.

- -

A file:// URI to the install location, or .xpi file, is available in installPath property of the bootstrap data structure passed to the startup(), shutdown(), install(), and uninstall() functions in what will be your bootstrap.js file (see below).

- -

How to get and load the data of of your add-on's files using the Add-on Manager API:

- -
// This is the OLD way of getting one of your files
-const myAddonID = ...;  // Just store a constant with your ID
-Components.utils.import("resource://gre/modules/AddonManager.jsm");
-AddonManager.getAddonByID(myAddonID,function(addon) {
-    var file = Services.io.newURI("resource://myAddon/filename.ext",null,null)
-                          .QueryInterface(Components.interfaces.nsIFileURL)
-                          .file;
-    var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
-                           .createInstance(Components.interfaces.nsIFileInputStream)
-                           .QueryInterface(Components.interfaces.nsISeekableStream);
-    stream.init(file, 0x01, 0444, 0);  // read-only, read by owner/group/others, normal behavior
-    /* do stuff */
-});
- -

This bit of code is paraphrased and probably not to be recommended as-is, but it should work. (note that the usage of an octal integer literal, while standard for handling permissions, is dangerous and deprecated; usage of use ES5 strict mode to disable this and other foot-guns is recommended) If you need to read/manipulate binary data, a nsIBinaryInputStream instance is what you'll use on that stream (e.g. 32-bit integers, or fun stuff like 48-bit integers). Not ideal, but it works and performs more than sufficiently well. All of that code above is no longer viable if you also go extractionless (which you should).

- -

Step 3a: Option 1: Use nsIZipReader

- -
let zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"]
-                          .createInstance(Components.interfaces.nsIZipReader);
-zipReader.open(addonData.installPath);
-...
-
- -

From there you can open nsIInputStreams, extract files, or perform some other functions. Worst case would be that you extract a file to a temporary location and then use nsIFile operations upon the extracted file.

- -

Step 3b: Option 2: Use XMLHttpRequest

- -

Now, how do we replace that? The answer to that question is to load your file from a chrome:// URI using XMLHttpRequest. You may now have another question: wait, what does this have to do with XML or HTTP? The answer to that question is, of course, nothing. XMLHttpRequest is an API created by Microsoft, adopted by Mozilla and other vendors, and hacked into a Swiss Army knife of file loading. You can use it in a web page to fetch a file from your server and you can use it in your add-on to fetch a local file from your installation. The name is a vestigial structure that just makes things confusing. It is nonetheless the "Correct" and best way to do things. It's available in the global for a window, but in JSM you'll need to fetch it from an interface:

- -
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1",
-                                              "nsIXMLHttpRequest");
- -

Here's how to load a file using it:

- -
function loadFile(url,type,returnresult)
-{
-    var request = new XMLHttpRequest();
-    request.open("GET", url, true);  // async=true
-    request.responseType = type;
-    request.onerror = function(event) {
-        logErrorMessage("Error attempting to load: " + url);
-        returnresult(null);
-    };
-    request.onload = function(event) {
-        if (request.response)
-            returnresult(request.response);
-        else
-            request.onerror(event);
-    };
-    request.send();
-}
-loadFile("chrome://myAddon/content/filename.ext",dataType,function(data) {
-    /* do stuff with data */
-});
- -

Note: When using XMLHttpRequest to access a file:// URL the request.status is not properly set to 200 to indicate success. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true.

- -

If your file is text, use "text" as your data type. If you're getting JSON this way make sure to explicitly set the type as "text" if you intend to parse it yourself. Even though it says that the default type is "text", Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with the type. MDN says you can set the type to "json" instead, if you prefer to have it parse things for you.

- -

If your file is not text or JSON, then you're going to want to read binary data. The new way to do this is to use JavaScript typed arrays. Specify "arraybuffer" as your data type to get one from your XMLHttpRequest. To access that data you're going to need a data view to look at your typed array with. Data that's homogeneous might get away with using something like Uint32Array or one of the other standard typed array views, but it's probably a bad idea. The basic typed array views are not endian-safe. This is incredibly stupid. You'd think such an important new JavaScript feature made available for web content and chrome alike would at least have a way to set and keep track of endianness, but no, it doesn't. Don't use any of the basic typed arrays for any data you did not earlier write into them in the same program session. Also, they're not particularly helpful if your data isn't all of the exact same type (which it probably isn't).

- -

The solution to read arbitrary binary data, of various sizes, in an endian-safe way, is to use DataView. The other typed array stuff is viable in Firefox 4+. This wasn't added until Firefox 15. If you were using nsIBinaryInputStream or anything similar, figuring out DataView will be fairly straightforward. Just read the docs and it's pretty simple. It will probably be notably faster than whatever you were doing before.

- -

Reportedly XMLHttpRequest doesn't work reliably when used in JSM under versions of Firefox less than 16, however as previously mentioned, this guide should be taken as requiring Firefox 17+.

- -

Step 4: Manually handle default preferences

- -

Normal extensions load default preferences from a standardized file automatically. Restartless extensions don't (for no good reason). This part is fairly easy to implement yourself, at least. Here are some functions to handle this:

- -
function getGenericPref(branch,prefName)
-{
-    switch (branch.getPrefType(prefName))
-    {
-        default:
-        case 0:   return undefined;                      // PREF_INVALID
-        case 32:  return getUCharPref(prefName,branch);  // PREF_STRING
-        case 64:  return branch.getIntPref(prefName);    // PREF_INT
-        case 128: return branch.getBoolPref(prefName);   // PREF_BOOL
-    }
-}
-function setGenericPref(branch,prefName,prefValue)
-{
-    switch (typeof prefValue)
-    {
-      case "string":
-          setUCharPref(prefName,prefValue,branch);
-          return;
-      case "number":
-          branch.setIntPref(prefName,prefValue);
-          return;
-      case "boolean":
-          branch.setBoolPref(prefName,prefValue);
-          return;
-    }
-}
-function setDefaultPref(prefName,prefValue)
-{
-    var defaultBranch = Services.prefs.getDefaultBranch(null);
-    setGenericPref(defaultBranch,prefName,prefValue);
-}
-function getUCharPref(prefName,branch)  // Unicode getCharPref
-{
-    branch = branch ? branch : Services.prefs;
-    return branch.getComplexValue(prefName, Components.interfaces.nsISupportsString).data;
-}
-function setUCharPref(prefName,text,branch)  // Unicode setCharPref
-{
-    var string = Components.classes["@mozilla.org/supports-string;1"]
-                           .createInstance(Components.interfaces.nsISupportsString);
-    string.data = text;
-    branch = branch ? branch : Services.prefs;
-    branch.setComplexValue(prefName, Components.interfaces.nsISupportsString, string);
-}
- -

Just grab the above, move your default preferences file to your chrome mapping, and then do the following line once during your startup:

- -
Services.scriptloader.loadSubScript("chrome://myAddon/content/defaultprefs.js",
-                                    {pref:setDefaultPref} );
-
- -

That's it. Once you've got the machinery to load and save preferences without having to jump through the various pref type hoops the actual preferences API sends you through, loading the actual preferences file is one line. I'd generally still recommend using the type specific functions for each pref individually, but to load the defaults just use the generic functions above and it's quite simple. The other generic functions are provided above in case you need them. Unfortunately, the built in APIs for dealing with preferences are missing this basic stuff, and its plain text handling doesn't work with Unicode properly.

- -

Step 4a: Another way to handle default preferences

- -

If you want to keep your preference file in defaults/preferences/, the approach above only works as long as your extension is unpacked. For packed extensions (the default), you can either load a module similar to Firebug’s prefLoader.js or load this workaround module.

- -

Step 5: No more internal JAR files

- -

You know how I've been mentioning extractionless add-ons every once in a while thus far? Well, you should probably consider switching to be extractionless when you go restartless. An old-style add-on installer is packaged something like this:

- -
myAddon.xpi file (glorified ZIP)
-└─ chrome.manifest
-└─ install.rdf
-└─ chrome folder
-  └─ myAddon folder
-    └─ content.jar file
-      └─ content folder (most files go here)
-      └─ locale folder (your locale files go here)
- -

In versions of Firefox prior to 4.0 (Gecko 2.0), the XPI would be extracted into a folder in your profile's extensions folder. In current versions it stays unextracted as an XPI. If you were using input streams you already had to deal with this because they weren't an option without extraction. Opting-out to extractionlessness is done via the "unpack" flag in install.rdf.

- -

Why the internal JAR? Well, two reasons:

- -
    -
  1. Prior to extractionless add-ons, all of your files got extracted. Putting them in one single JAR file made all your stuff load in one file read, which was faster. Extractionless XPIs are bascially a standardization of this idea.
  2. -
  3. XPI files are glorified ZIPs, and ZIP compression is horrible. Doing anuncompressed internal JAR (aka, another ZIP) acts like a poor-man's solid archive and significantly boosts the overall compression ratio of the XPI, resulting in smaller installers and updates.
  4. -
- -

So, it's pretty much internal JARor extractionless XPI. Well, you can't use an internal JAR anymore. Firefox aggressively caches add-on data a bit too much. Your restartless add-on won't actually reload some types of files if they are in a JAR and the add-on is updated without a restart. The big culprits are JSM files and locale files (namely property files), though in some situations this is true for dynamically loaded image files too. You're still going to have to manually clear the chrome cache on add-on shutdown to work around this, but that doesn't seem to be enough with an internal JAR. So, time to switch to extractionless, too. See here for the list of stuff you can't have in addition to no resource:// URIs or file:// URIs to files inside your XPI.

- -

If you actually can't find a way to go fully extractionless, you could hack together some combination of internal JAR(s) and extracted files. It can be done. However, you really should go extractionless. Firefox profiles aren't the pristine environment they're supposed to be. Software that pretends to be designed to protect security or privacy that some users have installed will sometimes delete files. There have been plenty of reports of add-on franken-installs with files of two versions mixed together. This might be due to malware or a bug in Firefox. In any case, I have noticed a significant improvement in reliability by going fully extractionless. Installing and updating a single file is far more idiot-proof.

- -

Step 6: No more XUL overlays

- -

Ok, now we're getting into some more drastic changes. You won't be able to use your chrome.manifest to load XUL overlays anymore with a restartless add-on. You could look into dynamically loading and unloading your overlay, however dynamically manipulating the DOM of your XUL window is usually the more straightforward route.

- -

Figure out what XUL elements you need to create for your add-on to add your interface, where it needs to go into a XUL window, and how to do it. Docs: document.getElementByID(), document.createElement(), Element reference, Node reference (DOM elements are also nodes).

- -

You'll need to write two functions. One to take a XUL window object and then create and add your elements, and then another to find your elements and remove them from the window object. The former will need to be run on add-on startup and the later on add-on shutdown. Until you get your bootstrap.js running you should use a basic overlay onto the XUL window with an event listener for "load" to catch overlay load and then run your manual UI construction function.

- -

Step 6a. Details on adding elements dynamically to chrome XUL window

- -

There is a way that makes constructing of UI a lot similar to the way it was made with XUL overlay. It involves using firebug.sdk. The next is example of the code:

- -
var overlay =
-  TOOLBARBUTTON(toolbarButtonAttrs,
-    PANEL({'id': 'thepanel', 'type': 'arrow'},
-      HBOX({'align': 'start'},
-        VBOX(
-          HBOX({'class': 'pixel-hbox'},
-            DESCRIPTION({'value': this.stringBundle.GetStringFromName('firexPixel.opacity')}),
-            HTMLINPUT({'id': 'opacity-range', 'type': 'range', 'min': '0', 'max': '10'})
-          ),
-          HBOX({'id': 'pixel-coords', 'class': 'pixel-hbox'},
-            LABEL({'control': 'coord-x', 'value': 'X:'}),
-            TEXTBOX({'id': 'coord-x', 'class': 'coord-box', 'placeholder' : '0'}),
-            LABEL({'control': 'coord-y', 'value': 'Y:'}),
-            TEXTBOX({'id': 'coord-y', 'class': 'coord-box', 'placeholder': '0'})
-         ...
-
- -

That way you build elements hierarchy with not much interaction with DOM, plus you can see tag properties and it children in a nice, structured way, just like in overlay.xul. You can find working example here. It involves using of firebug.sdk xul.js with few modifications.

- -

Step 7: Manually handle global CSS Stylesheets

- -

Any Global CSS style sheets which you are using will need to be registered upon load and unregistered when your extension is unloaded. Any CSS files used in any of your own XUL files will function normally without any extra work needed.

- -
Components.utils.import("resource://gre/modules/Services.jsm");
-var styleSheets = ["chrome://myExtension/skin/myStyleSheet.css"];
-
-function startup(data,reason)
-{
-...
-    // Load stylesheets
-    let styleSheetService= Components.classes["@mozilla.org/content/style-sheet-service;1"]
-                                     .getService(Components.interfaces.nsIStyleSheetService);
-    for (let i=0,len=styleSheets.length;i<len;i++) {
-        let styleSheetURI = Services.io.newURI(styleSheets[i], null, null);
-        styleSheetService.loadAndRegisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
-    }
-...
-}
-
-function shutdown(data,reason)
-{
-...
-    // Unload stylesheets
-    let styleSheetService = Components.classes["@mozilla.org/content/style-sheet-service;1"]
-                                      .getService(Components.interfaces.nsIStyleSheetService);
-    for (let i=0,len=styleSheets.length;i<len;i++) {
-        let styleSheetURI = Services.io.newURI(styleSheets[i], null, null);
-        if (styleSheetService.sheetRegistered(styleSheetURI, styleSheetService.AUTHOR_SHEET)) {
-            styleSheetService.unregisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
-        }
-    }
-...
-
- -

Step 8: Window icons

- -

Firefox does not scan the chrome/icons/default directory of restartless or extrationless extensions for window icons.  If you are using custom window icons, they will need to be moved to %MozDir%/icons/default/ upon load of your extension.  Removal upon unload is not required, but you must be able to handle overwriting them upon load.  This is because your unload() will not always be called prior to an upgrade (e.g. upgrade might take place while the application is not running). Further, this is a generic location for icons and the icon may still be in use by a different profile.  Thus, you will probably want to use version numbers in the icon name (the ID of the window for which the icon exists).

- -

Step 9: bootstrap.js

- -

A bootstrap.js file in the root of your XPI, next to your chrome.manifest and install.rdf, will be the heart of your restartless add-on. Think of it as main.c, but for JavaScript based Firefox restartless add-ons. A basic bootstrap.js file:

- -
Components.utils.import("resource://gre/modules/Services.jsm");
-function startup(data,reason) {
-    Components.utils.import("chrome://myAddon/content/myModule.jsm");
-    myModule.startup();  // Do whatever initial startup stuff you need to do
-
-    forEachOpenWindow(loadIntoWindow);
-    Services.wm.addListener(WindowListener);
-}
-function shutdown(data,reason) {
-    if (reason == APP_SHUTDOWN)
-        return;
-
-    forEachOpenWindow(unloadFromWindow);
-    Services.wm.removeListener(WindowListener);
-
-    myModule.shutdown();  // Do whatever shutdown stuff you need to do on addon disable
-
-    Components.utils.unload("chrome://myAddon/content/myModule.jsm");  // Same URL as above
-
-    // HACK WARNING: The Addon Manager does not properly clear all addon related caches on update;
-    //               in order to fully update images and locales, their caches need clearing here
-    Services.obs.notifyObservers(null, "chrome-flush-caches", null);
-}
-function install(data,reason) { }
-function uninstall(data,reason) { }
-function loadIntoWindow(window) {
-/* call/move your UI construction function here */
-}
-function unloadFromWindow(window) {
-/* call/move your UI tear down function here */
-}
-function forEachOpenWindow(todo)  // Apply a function to all open browser windows
-{
-    var windows = Services.wm.getEnumerator("navigator:browser");
-    while (windows.hasMoreElements())
-        todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
-}
-var WindowListener =
-{
-    onOpenWindow: function(xulWindow)
-    {
-        var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                              .getInterface(Components.interfaces.nsIDOMWindow);
-        function onWindowLoad()
-        {
-            window.removeEventListener("load",onWindowLoad);
-            if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser")
-                loadIntoWindow(window);
-        }
-        window.addEventListener("load",onWindowLoad);
-    },
-    onCloseWindow: function(xulWindow) { },
-    onWindowTitleChange: function(xulWindow, newTitle) { }
-};
-
- -

As mentioned above, Components.utils.unload() will not work properly if the JSM file it is unloading is in a JAR. Also make sure to only unload your own JSM files to avoid accidentally breaking things horribly.

- -

For tearing down and cleaning up on a per-window basis, there is another route you can take. Instead of directly calling your tear down function, make your unloadFromWindow() something like this:

- -
function unloadFromWindow(window)
-{
-    var event = window.document.createEvent("Event");
-    event.initEvent("myAddonName-unload",false,false);
-    window.dispatchEvent(event);
-}
-
- -

In each window you can then register on startup to listen for your custom "myAddonName-unload" event and just tear down and clean up when that event or a regular "unload" event comes in.

- -

Step 10: Bypass cache when loading properties files

- -

The above will get you a working add-on that will install without a Firefox restart. It will even get you a working add-on that will update without a Firefox restart... usually. Some parts work only if you don't look too closely; localization is one of them. As mentioned in the previous section, you'll need to clear the chrome caches on add-on shutdown, namely for chrome images and properties files. Doing this will get an update's new properties file to load, however sometimes this will instead produce an error on the next property access. It just doesn't seem that it can reliably clear the cache correctly, for whatever reason. String changes seem to be fine, however the addition or removal of strings cansometimes produce this error. It's not reliably reproducible, but it does happen.Yes, this is a pain in the ass.

- -

The suggestion that seems to work is to use a hack to bypass the string bundle cache. You should still be caching a reference to your string bundle on add-on startup, preferably using XPCOMUtils.jsm to lazily load the file. For example:

- -
Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyGetter(this, "strings", function() {
-    return loadPropertiesFile("chrome://myAddon/locale/mystrings.properties");
-});
-function loadPropertiesFile(path)
-{
-    /* HACK: The string bundle cache is cleared on addon shutdown, however it doesn't appear to do so reliably.
-       Errors can erratically happen on next load of the same file in certain instances. (at minimum, when strings are added/removed)
-       The apparently accepted solution to reliably load new versions is to always create bundles with a unique URL so as to bypass the cache.
-       This is accomplished by passing a random number in a parameter after a '?'. (this random ID is otherwise ignored)
-       The loaded string bundle is still cached on startup and should still be cleared out of the cache on addon shutdown.
-       This just bypasses the built-in cache for repeated loads of the same path so that a newly installed update loads cleanly. */
-    return Services.strings.createBundle(path + "?" + Math.random());
-}
-
- -

Just do strings.GetStringFromName(stringID) as you normally would. The lazy getter magic will cause the file to be automatically loaded the first time it is needed, after which point a reference to the loaded string bundle will be stored in "strings" for future accesses. You still need to clear the cache on add-on shutdown, however it will now also load cleanly on add-on updates. The old file should still be cleared.

- -

Put it all together

- -

That should be all the pieces. Your chrome.manifest will have just chrome and locale (and possibly skin) mappings in it now. No resource mappings or chrome overlays. The new entry point for your add-on is via bootstrap.js:startup() rather than a "load" handler in a XUL overlay.

- -

Your localization handling should be unaffected by your transition to a restartless/extractionless add-on so long as you properly clear the chrome cache on add-on shutdown and load your properties files using the method listed above. Your property files and DTD files loaded from chrome:// URIs should work just as before. This is all assuming a minimum version of Firefox 17+ (or other Gecko 17+ application) which you should remember to state explicitly in your install.rdf.

- -

Just remember that whatever you start you also need to have the ability to undo. In order for your add-on to reliably update without a restart it needs to be able to shutdown/disable cleanly.

- -

Also note that once you do get this all up and running, your users will still have to restart Firefox once to install your first restartless update. While your new add-on may not need a restart to install, if you're updating from an old version that is not restartless then it will need a restart touninstall that first.

- -
-

This tutorial was originally written by Dave Garrett from his experience porting the Flagfox extension.

-
- -

Further reading

- - diff --git a/files/ru/mozilla/add-ons/overlay_extensions/index.html b/files/ru/mozilla/add-ons/overlay_extensions/index.html deleted file mode 100644 index ceac592b8d..0000000000 --- a/files/ru/mozilla/add-ons/overlay_extensions/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Overlay extensions -slug: Mozilla/Add-ons/Overlay_Extensions -tags: - - Add-ons - - Extensions - - Landing - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Overlay_Extensions ---- -

Эта страница содержит ссылки на документы с описанием подхода к разработке расширений для приложений, работающих на движке Gecko, которые используют:

- - - -

До релиза Firefox 4 и до движка Gecko 2.0 это был единственный способ разработки расширений. Эта методология разработки была заменена на следующие две: расширения, не требующие перезапуска, и расширения на основе Add-on SDK. Они обе построены поверх первой. Привилегированные интерфейсы JavaScript API, описанные здесь могут быть также использованы в новых техниках разработки дополнений.

- -

Школа XUL

- -

Школа XUL - это комплексный учебник по разработке  дополнений, сфокусированный на разработке расширений для Firefox, но также подходящий для других приложений, основанных на движке Gecko.

- -

Ресурсы

- -
-
-
-
Настройка среды
-
Настройка приложений для разработки расширений.
-
XUL
-
Учебники и справочники по языку программирования, используемому XUL-расширениями.
-
Примеры кода
-
Примеры кода, которые пригодятся.
-
Установка расширений
-
Как установить расширение копированием файлов в установочный каталог.
-
Руководство разработчика дополнений для Firefox
-
Руководство по разработка расширений.
-
JavaScript-модули, доступные разработчику
-
JavaScript-модули доступные разработчику расширений.
-
Настройка расширения
-
-
- -
-
-
Как добавить свойства расширения, которые появятся в менеджере дополнений (Add-ons Manager).
-
FAQ
-
Решение некоторых общих проблем.
-
Сборка и установка расширения
-
Сборка и установка.
-
Создание бинарных расширений для Firefox
-
Создание бинарных расширений.
-
Создание расширения
-
Ещё один небольшой самоучитель по созданию расширения (только на русском языке)
-
Динамически изменяемый пользовательский интерфейс на XUL
-
В этой статье обсуждается управление XUL интерфейсами с использованием DOM и других API.
-
Настройка среды разработки расширений
-
В этой статье приводится несколько советов о том, как настроить ваше приложение Mozilla для удобной работы над расширениями.
-
Руководство по XUL
-
Руководство по XUL
-
-
-
diff --git a/files/ru/mozilla/add-ons/sdk/guides/index.html b/files/ru/mozilla/add-ons/sdk/guides/index.html deleted file mode 100644 index 1eacaad55a..0000000000 --- a/files/ru/mozilla/add-ons/sdk/guides/index.html +++ /dev/null @@ -1,365 +0,0 @@ ---- -title: Guides -slug: Mozilla/Add-ons/SDK/Guides -tags: - - Add-on SDK -translation_of: Archive/Add-ons/Add-on_SDK/Guides ---- -

- -
-

Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.

- -

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.

- -

Starting from Firefox 53, no new legacy add-ons will be accepted on addons.mozilla.org (AMO) for desktop Firefox and Firefox for Android.

- -

Starting from Firefox 57, only extensions developed using WebExtensions APIs will be supported on Desktop Firefox and Firefox for Android.

- -

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 use WebExtensions APIs if they can. See the "Compatibility Milestones" document for more information.

- -

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

-
- - - -

- -

This page lists more theoretical in-depth articles about the SDK.

- -
-

Contributor's guide

- -
-
-
-
Getting Started
-
Learn how to contribute to the SDK: getting the code, opening/taking a bug, filing a patch, getting reviews, and getting help.
-
Modules
-
Learn about the module system used by the SDK (which is based on the CommonJS specification), how sandboxes and compartments can be used to improve security, and about the built-in SDK module loader, known as Cuddlefish.
-
Classes and Inheritance
-
Learn how classes and inheritance can be implemented in JavaScript, using constructors and prototypes, and about the helper functions provided by the SDK to simplify this.
-
-
- -
-
-
Private Properties
-
Learn how private properties can be implemented in JavaScript using prefixes, closures, and WeakMaps, and how the SDK supports private properties by using namespaces (which are a generalization of WeakMaps).
-
Content Processes
-
The SDK was designed to work in an environment where the code to manipulate web content runs in a different process from the main add-on code. This article highlights the main features of that design.
-
Testing the Add-on SDK
-
Learn how to run the Add-on SDK test suites.
-
-
-
- -
-

SDK infrastructure

- -
-
-
-
Module structure of the SDK
-
The SDK, and add-ons built using it, are of composed from reusable JavaScript modules. This explains what these modules are, how to load modules, and how the SDK's module tree is structured.
-
SDK API lifecycle
-
Definition of the lifecycle for the SDK's APIs, including the stability ratings for APIs.
-
-
- -
-
-
Program ID
-
The Program ID is a unique identifier for your add-on. This guide explains how it's created, what it's used for and how to define your own.
-
Firefox compatibility
-
Working out which Firefox releases a given SDK release is compatible with, and dealing with compatibility problems.
-
-
-
- -
-

SDK idioms

- -
-
-
-
Working With Events
-
Write event-driven code using the the SDK's event emitting framework.
-
Content scripts guide
-
An overview of content scripts, including: what they are, what they can do, how to load them, how to communicate with them.
-
-
- -
-
-
Two Types of Scripts
-
This article explains the differences between the APIs available to your main add-on code and those available to content scripts.
-
-
-
- -
-

XUL migration

- -
-
-
-
XUL Migration Guide
-
Techniques to help port a XUL add-on to the SDK.
-
XUL versus the SDK
-
A comparison of the strengths and weaknesses of the SDK, compared to traditional XUL-based add-ons.
-
-
- -
-
-
Porting Example
-
A walkthrough of porting a relatively simple XUL-based add-on to the SDK.
-
-
-
- -
-

Multiprocess Firefox

- -
-
-
-
Multiprocess Firefox and the SDK
-
How to check whether your add-on is compatible with multiprocess Firefox, and fix it if it isn't.
-
-
- -
-
- -
-
-
-
-

Join the Add-on SDK community

- -
-
Choose your preferred method for joining the discussion:
- - -
- -
- -
-
-
-
diff --git "a/files/ru/mozilla/add-ons/sdk/guides/\321\201\320\272\321\200\320\270\320\277\321\202\321\213_\321\201\320\276\320\264\320\265\321\200\320\266\320\270\320\274\320\276\320\263\320\276/index.html" "b/files/ru/mozilla/add-ons/sdk/guides/\321\201\320\272\321\200\320\270\320\277\321\202\321\213_\321\201\320\276\320\264\320\265\321\200\320\266\320\270\320\274\320\276\320\263\320\276/index.html" deleted file mode 100644 index 59832331e8..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/guides/\321\201\320\272\321\200\320\270\320\277\321\202\321\213_\321\201\320\276\320\264\320\265\321\200\320\266\320\270\320\274\320\276\320\263\320\276/index.html" +++ /dev/null @@ -1,519 +0,0 @@ ---- -title: Скрипты Content Scripts -slug: Mozilla/Add-ons/SDK/Guides/Скрипты_содержимого -tags: - - Content script - - Дополнение -translation_of: Archive/Add-ons/Add-on_SDK/Guides/Content_Scripts ---- -
-

{{AddonSidebar}}

- -
-

Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.

-
- -

{{LegacyAddonsNotice}}

- -

Многим дополнениям (add-on) необходим доступ к веб-страницам и возможность их изменения. Но основной код дополнения не имеет прямого доступа к веб-содержимому. Взамен, SDK-дополнений необходим способ в коде, который даст доступ к веб-содержимому в отдельных скриптах, которые называются content scripts (скрипты содержимого). Эта страница описывает как разрабатывать и реализовывать content scripts.

- -

Скрипты content scripts, вероятно, один из наиболее сбивающих с толку аспектов при работе с SDK, но вам они скорее всего будут нужны. Существуют пять основных принципов:

- - - -

Следующее дополнение (полностью завершённое) показывает эти принципы. "main.js" прикрепляет content scripts к текущей вкладке, используя модуль tabs. В этом случае, content scripts передаётся, как строка. Скрипт content scripts просто заменяет содержимое страницы:

- -
// main.js
-var tabs = require("sdk/tabs");
-var contentScriptString = 'document.body.innerHTML = "<h1>this page has been eaten</h1>";'
-
-tabs.activeTab.attach({
-  contentScript: contentScriptString
-});
- -

Следующие высокоуровневые SDK-модули, могут использовать скрипты content scripts для изменения веб-страниц:

- - - -

В дополнение к этому, некоторые SDK компоненты пользовательского интерфейса - panel, sidebar, frame - заданы в помощью HTML, и необходимо использовать отдельные скрипты для взаимодействия с их контентом. В большинстве случаев они похожи на скрипты content scripts, но в данной статье они не описываются. Для изучения способов взаимодействия с данными модулями пользовательского интерфейса обратитесь к документации: panel, sidebar, frame.

- -

Почти все примеры дополнений, представленных в этом руководстве, доступны в полнофункциональном, но минимально необходимом, виде. На GitHub: addon-sdk-content-scripts repository.

- -

Загрузка content scripts

- -
-

Вы можете загрузить одиночный скрипт посредством задания строкового атрибута contentScript или contentScriptFile. Атрибут contentScript определяет строковое значение как сам скрипт:

- -
// main.js
-
-var pageMod = require("sdk/page-mod");
-var contentScriptValue = 'document.body.innerHTML = ' +
-                         ' "<h1>Page matches ruleset</h1>";';
-
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScript: contentScriptValue
-});
- -

Атрибут contentScriptFile определяет строковое значение как путь к ресурсу://URL-путь к скрипту, который находится в подкаталоге вашего дополнения. jpm не создаёт папку "data" по умолчанию, поэтому вы должны добавить её и положить внутрь файл content scripts.

- -

Следующее дополнение использует URL для ссылки на файл "content-script.js", находящийся в папке data в корне дополнения.

- -
// main.js
-
-var data = require("sdk/self").data;
-var pageMod = require("sdk/page-mod");
-
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScriptFile: data.url("content-script.js")
-});
- -
// content-script.js
-
-document.body.innerHTML = "<h1>Page matches ruleset</h1>";
- -
-

Начиная с Firefox 34 и далее , вы можете использовать "./content-script.js" как синоним для self.data.url("content-script.js"). Поэтому можно переписать код main.js, указанный выше, следующим образом:

- -
var pageMod = require("sdk/page-mod");
-
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScriptFile: "./content-script.js"
-});
-
-
- -
-

Настоятельно рекоммендуется использовать  contentScript только для очень простых скриптов или статичных строк: если это не так, то могут возникнуть проблемы с принятием Вашего дополнения на AMO (addons.mozilla.org).

- -

Содержите ваши скрипты в отдельном файле и загружайте их, используя contentScriptFile. Это сделает ваш код проще в поддержке, отладке, безопаснее, удобочитаемее.

-
- -

Для любого из параметров contentScript или contentScriptFile вы можете загружать несколько скриптов, передавая массив строк:

- -
// main.js
-
-var tabs = require("sdk/tabs");
-
-tabs.on('ready', function(tab) {
-  tab.attach({
-      contentScript: ['document.body.style.border = "5px solid red";', 'window.alert("hi");']
-  });
-});
-
- -
// main.js
-
-var data = require("sdk/self").data;
-var pageMod = require("sdk/page-mod");
-
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScriptFile: [data.url("jquery.min.js"), data.url("my-content-script.js")]
-});
- -

Если так сделать, то скрипты смогут взаимодействовать друг с другом, как скрипты загружаемые на одной web-странице.

- -

Можно использовать параметры contentScript and contentScriptFile одновременно. В таком случае скрипты, загружаемые contentScriptFile  загрузятся до contentScript. Это похволяет загружать библиотеки JavaScript, такие как jQuery по URL, а затем использвать их в простом скрипте, загруженном через contentScript:

- -
// main.js
-
-var data = require("sdk/self").data;
-var pageMod = require("sdk/page-mod");
-
-var contentScriptString = '$("body").html("<h1>Page matches ruleset</h1>");';
-
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScript: contentScriptString,
-  contentScriptFile: data.url("jquery.js")
-});
- -
-

Настоятельно рекоммендуется использовать  contentScript только для очень простых скриптов или статичных строк: если это не так, то могут возникнуть проблемы с принятием Вашего дополнения на AMO (addons.mozilla.org).

- -

Содержите ваши скрипты в отдельном файле и загружайте их, используя contentScriptFile. Это сделает ваш код проще в поддержке, отладке, безопаснее, удобочитаемее.

-
- -

Определение момента (времени) подключения скрипта

- -

Опция contentScriptWhen определяет момент, когда content script должен быть загружен. Возможные варианты:

- -
    -
  • "start": загрузить сразу после того, как элемент документа страницы вставляется в DOM. В таком случае DOM-контент ещё пока не загружен, поэтому скрипт не может работать с ним.
  • -
  • "ready": загрузить скрипт после того, как DOM страницы загружен: то есть в точке активации событий DOMContentLoaded. В этот момент content scripts уже могут взаимодействовать с DOM-контентом, но загрузка внешних CSS и картинок ещё могла не завершиться.
  • -
  • "end": загрузить скрипт после завершения загрузки всего контента (DOM, JS, CSS, картинки), в то время, как активируется событие window.onload event.
  • -
- -

Значение по умолчанию "end".

- -

Обратите внимание, что tab.attach() не имеет параметра contentScriptWhen, потому что он обычно вызывается после загрузки страницы.

- -

Передача конфигурационных опций

- -

Атрибут contentScriptOptions это JSON-объект, который используется скриптом как read-only значение доступное через свойство self.options:

- -
// main.js
-
-var tabs = require("sdk/tabs");
-
-tabs.on('ready', function(tab) {
-  tab.attach({
-      contentScript: 'window.alert(self.options.message);',
-      contentScriptOptions: {"message" : "hello world"}
-  });
-});
- -

Могут быть использованы любые варианты JSON-объектов (object, array, string, etc.).

- -

Доступ к DOM

- -

Скрипты content scripts могут иметь доступ к DOM страницы, конечно, только те скрипты, которые уже загрузились на странице. При этом скрипты content scripts изолированы от скриптов web-страницы:

- -
    -
  • content scripts не видят объектов JavaScript, добавленных скриптами web-страницы.
  • -
  • Если скриты web-страницы переопределят поведения каких-либо DOM-объектов, то скрипты content script обнаружат исходное поведение.
  • -
- -

То же происходит в обратную сторону: скрипты web-страницы не увидят объектов JavaScript, добавленных скриптами content scripts.

- -

Например, рассмотрим страницу, где скрипты web-страницы создают переменную foo в объекте window:

- -
<!DOCTYPE html">
-<html>
-  <head>
-    <script>
-    window.foo = "hello from page script"
-    </script>
-  </head>
-</html>
- -

Другой скрипт (но тоже page-script), загруженный на страницу после этого скрипта (указанного выше), будет иметь доступ к foo. Но скрипт content script нет:

- -
// main.js
-
-var tabs = require("sdk/tabs");
-var mod = require("sdk/page-mod");
-var self = require("sdk/self");
-
-var pageUrl = self.data.url("page.html")
-
-var pageMod = mod.PageMod({
-  include: pageUrl,
-  contentScript: "console.log(window.foo);"
-})
-
-tabs.open(pageUrl);
- -
console.log: my-addon: null
-
- -

Есть веские причины для изоляции. Во-первых, из content script не утекают объекты в web-страницу, что потенциально является дырой в безопасности. Во-вторых, content scripts могут не беспокоиться о пересечении объектов с объектами, созданных скриптами web-страницы.

- -

Такая изоляция необходима, например, в случае, если web-страница загружает библиотеку jQuery, но content script не увидит объектов, созданных этой библиотекой. В этом случае content script может добавить свою собственный jQuery-объект, который не пересечётся со страничным объектом.

- -

Взаимодействие со скриптами web-страницы

- -

Обычно изоляция content scripts и page scripts (скрипты web-страницы) необходима. Но иногда вы захотите наладить такое взаимодействие: вы можете захотеть иметь общие объекты между content scripts и page scripts или передевать между ними сообщения. Если появится такая необходимость, то прочтите о взаимодействии со скриптами web-страницы (interacting with page scripts).

- -

Прослушивание событий

- -

Вы можете прослушивать события DOM в скриптах content scripts также, как в обычных скриптах web-страницы. Но есть два важных отличия:

- -

Первое. Если вы определите слушатель через передачу строки в функцию setAttribute(), то слушатель будет вызываться в контексте web-страницы, поэтому он не будет иметь доступа ни к каким переменным, определённым в content script.

- -

Например, при выполнении в данном content script появится ошибка "theMessage is not defined":

- -
var theMessage = "Hello from content script!";
-anElement.setAttribute("onclick", "alert(theMessage);");
- -

Второе. Если вы определите слушатель напрямую через GlobalEventHandlers, например на onclick, то такое определение может быть переопределено на web-странице. Например, здесь представлен add-on, который пытается добавить обработчик click-события при помощи присвоения window.onclick:

- -
var myScript = "window.onclick = function() {" +
-               "  console.log('unsafewindow.onclick: ' + window.document.title);" +
-               "}";
-
-require("sdk/page-mod").PageMod({
-  include: "*",
-  contentScript: myScript,
-  contentScriptWhen: "start"
-});
- -

Это всё будет прекрасно работать на многих страницах, но не сработает там, где также присваивается onclick:

- -
<html>
-  <head>
-  </head>
-  <body>
-    <script>
-    window.onclick = function() {
-      window.alert("it's my click now!");
-    }
-    </script>
-  </body>
-</html>
- -

По этим причинам, лучший вариант для добавления слушалелей это использование addEventListener(), определяющем функцию:

- -
var theMessage = "Hello from content script!";
-
-anElement.onclick = function() {
-  alert(theMessage);
-};
-
-anotherElement.addEventListener("click", function() {
-  alert(theMessage);
-});
- -

Взаимодействие с скриптом дополнения (add-on)

- -

Для организации взаимодействия друг с другом скрипта дополнения (add-on script) и скрипта content script нужно обоим дать доступ к объекту port.

- -
    -
  • для отправки сообщений используется port.emit()
  • -
  • для получения сообщений - port.on()
  • -
- -

Сообщения асинхронны: то есть, отправитель не ждёт ответа от получателя, а только отправляет сообщение и продолжает работать дальше.

- -

Вот пример простого дополнения, которое отправляет сообщение скрипту content script, используя port:

- -
// main.js
-
-var tabs = require("sdk/tabs");
-var self = require("sdk/self");
-
-tabs.on("ready", function(tab) {
-  var worker = tab.attach({
-    contentScriptFile: self.data.url("content-script.js")
-  });
-  worker.port.emit("alert", "Message from the add-on");
-});
-
-tabs.open("http://www.mozilla.org");
- -
// content-script.js
-
-self.port.on("alert", function(message) {
-  window.alert(message);
-});
- -
-

Модуль context-menu не использует данную модель коммуникации. Для изучения варианта взаимодействия скриптов content scripts, загруженных с использованием context-menu, смотрите context-menu documentation

-
- -

Доступ к порту в content script

- -

В скрипте content script объект port доступен через свойство глобального объекта self.  Чтобы послать сообщение из content script:

- -
self.port.emit("myContentScriptMessage", myContentScriptMessagePayload);
- -

Чтобы получить сообщение из кода дополнения:

- -
self.port.on("myAddonMessage", function(myAddonMessagePayload) {
-  // Handle the message
-});
- -
-

Учтите, что глобальный объект self совершенно отличается от модуля self module, предоставляющим API дополнению для доступа к его файлам и ID.

-
- -

Доступ к порту в скрипте дополнения (add-on script)

- -

В коде дополнения канал взаимодействия между дополнением и конкретным content script инкапсулируется посредством объекта worker. Поэтому объект port для для связи со скриптом content script это свойство связанного worker.

- -

Тем не менее, объект worker не расширен на код дополнения так же, как в других модулях.

- -

Сообщения из page-worker

- -

Объект page-worker интегрирует в себе worker API. Поэтому для получения сообщений от скрипта content script, ассоциированного с page-worker нужно использовать pageWorker.port.on():

- -
// main.js
-
-var self = require("sdk/self");
-
-var pageWorker = require("sdk/page-worker").Page({
-  contentScriptFile: self.data.url("content-script.js"),
-  contentURL: "http://en.wikipedia.org/wiki/Internet"
-});
-
-pageWorker.port.on("first-para", function(firstPara) {
-  console.log(firstPara);
-});
- -

Для отправки пользовательских сообщений их дополнения нужно вызвать pageWorker.port.emit():

- -
// main.js
-
-var self = require("sdk/self");
-
-var pageWorker = require("sdk/page-worker").Page({
-  contentScriptFile: self.data.url("content-script.js"),
-  contentURL: "http://en.wikipedia.org/wiki/Internet"
-});
-
-pageWorker.port.on("first-para", function(firstPara) {
-  console.log(firstPara);
-});
-
-pageWorker.port.emit("get-first-para");
- -
// content-script.js
-
-self.port.on("get-first-para", getFirstPara);
-
-function getFirstPara() {
-  var paras = document.getElementsByTagName("p");
-  if (paras.length > 0) {
-    var firstPara = paras[0].textContent;
-    self.port.emit("first-para", firstPara);
-  }
-}
- -

Сообщения из page-mod

- -

Один объект page-mod может привязать свои скрипты к нескольким страницам, каждая из них со своим контекстом, в котором запускаются content scripts. Поэтому для каждой страницы необходим отдельный канал (worker) связи.

- -

page-mod не интегрирует в себе worker API напрямую. Вместо этого, когда скрипт content script привязывается к странице, page-mod бросает событие attach тому слушателю, который связан с worker. Создавая слушатель для события attach, вы можете получить доступ через объект port к тому скрипту content scripts, который связан с нужной страницей (через page-mod):

- -
// main.js
-
-var pageMods = require("sdk/page-mod");
-var self = require("sdk/self");
-
-var pageMod = pageMods.PageMod({
-  include: ['*'],
-  contentScriptFile: self.data.url("content-script.js"),
-  onAttach: startListening
-});
-
-function startListening(worker) {
-  worker.port.on('click', function(html) {
-    worker.port.emit('warning', 'Do not click this again');
-  });
-}
- -
// content-script.js
-
-window.addEventListener('click', function(event) {
-  self.port.emit('click', event.target.toString());
-  event.stopPropagation();
-  event.preventDefault();
-}, false);
-
-self.port.on('warning', function(message) {
-  window.alert(message);
-});
-
- -

В дополнении, описанном выше, есть два сообщения:

- -
    -
  • click отправляется из page-mod в дополнение, когда пользователь кликает на элемент на web-странице
  • -
  • warning отправляет прикольную строчку обратно в объект page-mod
  • -
- -

Сообщения из Tab.attach()

- -

Функция Tab.attach() возвращает worker, который можно использовать для связи со скриптом content script(s).

- -

Следующее дополнение добавляет кнопку в Firefox: когда пользователь надимает её, то дополнение привязывает скрипт content script к активной вкладке, отправляет этому скрипту сообщение "my-addon-message" и ждёт ответ "my-script-response":

- -
//main.js
-
-var tabs = require("sdk/tabs");
-var buttons = require("sdk/ui/button/action");
-var self = require("sdk/self");
-
-buttons.ActionButton({
-  id: "attach-script",
-  label: "Attach the script",
-  icon: "./icon-16.png",
-  onClick: attachScript
-});
-
-function attachScript() {
-  var worker = tabs.activeTab.attach({
-    contentScriptFile: self.data.url("content-script.js")
-  });
-  worker.port.on("my-script-response", function(response) {
-    console.log(response);
-  });
-  worker.port.emit("my-addon-message", "Message from the add-on");
-}
-
- -
// content-script.js
-
-self.port.on("my-addon-message", handleMessage);
-
-function handleMessage(message) {
-  alert(message);
-  self.port.emit("my-script-response", "Response from content script");
-}
- -

Описание port API

- -

Смотрите reference page for the port object.

-
- -

Описание postMessage API

- -

До того, как был введён объект port, дополнения и content scripts общались следующим образом, используя различные API:

- - - -

Данный API до сих пор доступно и документировано, но желательно использовать port API, описанный здесь выше. Исключением является модуль context-menu, который ещё использует postMessage.

- -

Взаимодействие скриптов content script со скриптами content script

- -

Скрипты content scripts могут взаимодействовать друг с другом напрямую если они загружены в одном контексте. Например, если один вызов Tab.attach() привязывает два скрипта content scripts, то они видят друг друга напрямую, как если два скрипта загружены на одну страницу. Но если вызвать Tab.attach() дважды, привязывая content scripts каждый раз, то они уже не будут загружены в одном контексте, и дожны взаимодействовать способами как скрипты из разных контекстов. Один из вариантом это пересылать сообщения через основной код дополнения, используя port API с передачей сообщения другим скриптам context script. Этои вариант будет работать независимо от контекста, в котором загружен скрипт content script.

- -

В отдельном случае, когда два скрипта загружены на одной странице, существует возможность для обоих скриптов content scripts взаимодействовать друг с другом, используя DOM postMessage() API или CustomEvent. Следующее дополнение показывает как скрипт content script, добавленный через page-mod, получает событие CustomEvent, отправленное из context-menu, когда элемент меню был кликнут. Скрипт page-mod будет отображать алерт с URL той ссылки, по которой было отображено контекстное меню. URL передан в скрипт page-mod с использованием CustomEvent.

- -
var pageMod = require("sdk/page-mod");
-pageMod.PageMod({
-  include: "*.mozilla.org",
-  contentScript: 'function contextMenuAlert(href) {'
-               + '    window.alert("The context menu was clicked on URL:\\n" + href);'
-               + '};'
-               + 'window.addEventListener("myAddonId-contextMenu-clicked",'
-               + '    function(event){contextMenuAlert(event.detail);});'
-});
-
-let cm = require("sdk/context-menu");
-cm.Item({
-    label: "Alert URL",
-    context: [
-        cm.URLContext(["*.mozilla.org"]),
-        cm.SelectorContext("a[href]")
-    ],
-    contentScript: 'self.on("click", function (node, data) {'
-                 + '    var event = new CustomEvent("myAddonId-contextMenu-clicked",'
-                 + '                                {detail:node.href});'
-                 + '    window.dispatchEvent(event);'
-                 + '});'
-});
- -

Междоменные скрипты content script

- -

По умолчанию скрипты content script не имеют никаких междоменных привилегий. В частности, они не имеют доступа к содержимому в iframe, если содержимое получено из другого домена, или выполняются междоменные XMLHttpRequests.

- -

Однако, вы можете разрешить эти функции для заданных доменов, путём добавления их в package.json дополнения в ключе "cross-domain-content", который расположен в ключе "permissions". Смотрите статью междоменные скрипты содержимого.

-
diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html deleted file mode 100644 index 069cb199b2..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Страницы дополнения -slug: Mozilla/Add-ons/SDK/High-Level_APIs/addon-page -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/addon-page ---- -

{{AddonSidebar}}

- -

{{obsolete_header(35)}}

- -

Создание простых страниц

- -

Применеие

- -

С помошью Add-on SDK Вы можете представлять данные пользователю, такие как руководство по использованию вашего дополнения во вкладке браузера. Вы можете подгружать содержимое из HTML файла в "data" директории дополнения.

- -
-

Заметка: Данный модульне влияет на браузер.

-
- -

Для подобных страниц, navigational elements such as the Awesome Bar, Search Bar, or Bookmarks Toolbar are not usually relevant and distract from the content you are presenting. The addon-page module provides a simple way to have a page which excludes these elements.

- -

Чтобы импортировать содержимое, используйте require(). После чего, данные загрузятся из "data/index.html" без элементов навигации:

- -
var addontab = require("sdk/addon-page");
-var data = require("sdk/self").data;
-
-require("sdk/tabs").open(data.url("index.html"));
-
- -

- -

Это влияет только на "data/index.html": остальные страницы отображаются нормально.

diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html deleted file mode 100644 index 2d88abc734..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html +++ /dev/null @@ -1,578 +0,0 @@ ---- -title: context-menu -slug: Mozilla/Add-ons/SDK/High-Level_APIs/context-menu -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/context-menu ---- -
-

Stable

-
-

Как добавить элемент меню, подменю и разделитель в контекстное меню страницы.

-

Использование

-

Instead of manually adding items when particular contexts occur and then removing them when those contexts go away, you bind items to contexts, and the adding and removing is automatically handled for you. Items are bound to contexts in much the same way that event listeners are bound to events. When the user invokes the context menu, all of the items bound to the current context are automatically added to the menu. If no items are bound, none are added. Likewise, any items that were previously in the menu but are not bound to the current context are automatically removed from the menu. You never need to manually remove your items from the menu unless you want them to never appear again.

-

For example, if your add-on needs to add a context menu item whenever the user visits a certain page, don't create the item when that page loads, and don't remove it when the page unloads. Rather, create your item only once and supply a context that matches the target URL.

-

Context menu items are displayed in the order created or in the case of sub menus the order added to the sub menu. Menu items for each add-on will be grouped together automatically. If the total number of menu items in the main context menu from all add-ons exceeds a certain number (normally 10 but configurable with the extensions.addon-sdk.context-menu.overflowThreshold preference) all of the menu items will instead appear in an overflow menu to avoid making the context menu too large.

-

Specifying Contexts

-

As its name implies, the context menu should be reserved for the occurrence of specific contexts. Contexts can be related to page content or the page itself, but they should never be external to the page.

-

For example, a good use of the menu would be to show an "Edit Image" item when the user right-clicks an image in the page. A bad use would be to show a submenu that listed all the user's tabs, since tabs aren't related to the page or the node the user clicked to open the menu.

-

The Page Context

-

First of all, you may not need to specify a context at all. When a top-level item does not specify a context, the page context applies. An item that is in a submenu is visible unless you specify a context.

-

The page context occurs when the user invokes the context menu on a non-interactive portion of the page. Try right-clicking a blank spot in this page, or on text. Make sure that no text is selected. The menu that appears should contain the items "Back", "Forward", "Reload", "Stop", and so on. This is the page context.

-

The page context is appropriate when your item acts on the page as a whole. It does not occur when the user invokes the context menu on a link, image, or other non-text node, or while a selection exists.

-

Declarative Contexts

-

You can specify some simple, declarative contexts when you create a menu item by setting the context property of the options object passed to its constructor, like this:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "My Menu Item",
-  context: cm.URLContext("*.mozilla.org")
-});
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConstructorDescription
PageContext() The page context.
SelectionContext() This context occurs when the menu is invoked on a page in which the user has made a selection.
SelectorContext(selector) This context occurs when the menu is invoked on a node that either matches selector, a CSS selector, or has an ancestor that matches. selector may include multiple selectors separated by commas, e.g., "a[href], img".
URLContext(matchPattern) This context occurs when the menu is invoked on pages with particular URLs. matchPattern is a match pattern string or an array of match pattern strings. When matchPattern is an array, the context occurs when the menu is invoked on a page whose URL matches any of the patterns. These are the same match pattern strings that you use with the page-mod include property. Read more about patterns.
PredicateContext(predicateFunction)predicateFunction is called when the menu is invoked, and the context occurs when the function returns a true value. The function is passed an object with properties describing the menu invocaton context.
arrayAn array of any of the other types. This context occurs when all contexts in the array occur.
-

Menu items also have a context property that can be used to add and remove declarative contexts after construction. For example:

-
var context = require("sdk/context-menu").SelectorContext("img");
-myMenuItem.context.add(context);
-myMenuItem.context.remove(context);
-

When a menu item is bound to more than one context, it appears in the menu when all of those contexts occur.

-

In Content Scripts

-

The declarative contexts are handy but not very powerful. For instance, you might want your menu item to appear for any page that has at least one image, but declarative contexts won't help you there.

-

When you need more control over the context in which your menu items are shown, you can use content scripts. Like other APIs in the SDK, the context-menu API uses content scripts to let your add-on interact with pages in the browser. Each menu item you create in the top-level context menu can have a content script.

-

A special event named "context" is emitted in your content scripts whenever the context menu is about to be shown. If you register a listener function for this event and it returns true, the menu item associated with the listener's content script is shown in the menu.

-

For example, this item appears whenever the context menu is invoked on a page that contains at least one image:

-
require("sdk/context-menu").Item({
-  label: "This Page Has Images",
-  contentScript: 'self.on("context", function (node) {' +
-                 '  return !!document.querySelector("img");' +
-                 '});'
-});
-

Note that the listener function has a parameter called node. This is the node in the page that the user context-clicked to invoke the menu. You can use it to determine whether your item should be shown.

-

You can both specify declarative contexts and listen for contexts in a content script. In that case, the declarative contexts are evaluated first, and your item is shown only when all declarative contexts are current and your context listener returns true.

-

If any declarative contexts are not current, then your context listener is never called. This example takes advantage of that fact. The listener can be assured that node will always be an image:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "A Mozilla Image",
-  context: cm.SelectorContext("img"),
-  contentScript: 'self.on("context", function (node) {' +
-                 '  return /mozilla/.test(node.src);' +
-                 '});'
-});
-

However, if you do combine SelectorContext and the "context" event, be aware that the node argument passed to the "context" event will not always match the type specified in SelectorContext.

-

SelectorContext will match if the menu is invoked on the node specified or any descendant of that node, but the "context" event handler is passed the actual node on which the menu was invoked. The example above works because <IMG> elements can't contain other elements, but in the example below, node.nodeName is not guaranteed to be "P" - for example, it won't be "P" if the user context-clicked a link inside a paragraph:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "A Paragraph",
-  context: cm.SelectorContext("p"),
-  contentScript: 'self.on("context", function (node) {' +
-                 '  console.log(node.nodeName);' +
-                 '  return true;' +
-                 '});'
-});
-

The content script is executed for every page that a context menu is shown for. It will be executed the first time it is needed (i.e. when the context menu is first shown and all of the declarative contexts for your item are current) and then remains active until you destroy your context menu item or the page is unloaded.

-

Handling Menu Item Clicks

-

In addition to using content scripts to listen for the "context" event as described above, you can use content scripts to handle item clicks. When the user clicks your menu item, an event named "click" is emitted in the item's content script.

-

Therefore, to handle an item click, listen for the "click" event in that item's content script like so:

-
require("sdk/context-menu").Item({
-  label: "My Item",
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  console.log("Item clicked!");' +
-                 '});'
-});
-

Note that the listener function has parameters called node and data.

-

The "node" Argument

-

node is the node that the user context-clicked to invoke the menu.

- -

For example, suppose your add-on looks like this:

-
var script = "self.on('click', function (node, data) {" +
-             "  console.log('clicked: ' + node.nodeName);" +
-             "});";
-
-var cm = require("sdk/context-menu");
-
-cm.Item({
-  label: "body context",
-  context: cm.SelectorContext("body"),
-  contentScript: script
-});
-

This add-on creates a context-menu item that uses SelectorContext to display the item whenever the context menu is activated on any descendant of the <BODY> element. When clicked, the item just logs the nodeName property for the node passed to the click handler.

-

If you run this add-on you'll see that it always logs "BODY", even if you click on a paragraph element inside the page:

-
info: contextmenu-example: clicked: BODY
-

By contrast, this add-on uses the PageContext:

-
var script = "self.on('click', function (node, data) {" +
-             "  console.log('clicked: ' + node.nodeName);" +
-             "});";
-
-var cm = require("sdk/context-menu");
-
-cm.Item({
-  label: "body context",
-  context: cm.PageContext(),
-  contentScript: script
-});
-

It will log the name of the actual node clicked:

-
info: contextmenu-example: clicked: P
-

The "data" Argument

-

data is the data property of the menu item that was clicked. Note that when you have a hierarchy of menu items the click event will be sent to the content script of the item clicked and all ancestors so be sure to verify that the data value passed matches the item you expect. You can use this to simplify click handling by providing just a single click listener on a Menu that reacts to clicks for any child items.:

-
var cm = require("sdk/context-menu");
-cm.Menu({
-  label: "My Menu",
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  console.log("You clicked " + data);' +
-                 '});',
-  items: [
-    cm.Item({ label: "Item 1", data: "item1" }),
-    cm.Item({ label: "Item 2", data: "item2" }),
-    cm.Item({ label: "Item 3", data: "item3" })
-  ]
-});
-
-

Communicating With the Add-on

-

Often you will need to collect some kind of information in the click listener and perform an action unrelated to content. To communicate to the menu item associated with the content script, the content script can call the postMessage function attached to the global self object, passing it some JSON-able data. The menu item's "message" event listener will be called with that data.

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "Edit Image",
-  context: cm.SelectorContext("img"),
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  self.postMessage(node.src);' +
-                 '});',
-  onMessage: function (imgSrc) {
-    openImageEditor(imgSrc);
-  }
-});
-

Updating a Menu Item's Label

-

Each menu item must be created with a label, but you can change its label later using a couple of methods.

-

The simplest method is to set the menu item's label property. This example updates the item's label based on the number of times it's been clicked:

-
var numClicks = 0;
-var myItem = require("sdk/context-menu").Item({
-  label: "Click Me: " + numClicks,
-  contentScript: 'self.on("click", self.postMessage);',
-  onMessage: function () {
-    numClicks++;
-    this.label = "Click Me: " + numClicks;
-    // Setting myItem.label is equivalent.
-  }
-});
-

Sometimes you might want to update the label based on the context. For instance, if your item performs a search with the user's selected text, it would be nice to display the text in the item to provide feedback to the user. In these cases you can use the second method. Recall that your content scripts can listen for the "context" event and if your listeners return true, the items associated with the content scripts are shown in the menu. In addition to returning true, your "context" listeners can also return strings. When a "context" listener returns a string, it becomes the item's new label.

-

This item implements the aforementioned search example:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "Search Google",
-  context: cm.SelectionContext(),
-  contentScript: 'self.on("context", function () {' +
-                 '  var text = window.getSelection().toString();' +
-                 '  if (text.length > 20)' +
-                 '    text = text.substr(0, 20) + "...";' +
-                 '  return "Search Google for " + text;' +
-                 '});'
-});
-

The "context" listener gets the window's current selection, truncating it if it's too long, and includes it in the returned string. When the item is shown, its label will be "Search Google for text", where text is the truncated selection.

-

Private Windows

-

If your add-on has not opted into private browsing, then any menus or menu items that you add will not appear in context menus belonging to private browser windows.

-

To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module.

-

More Examples

-

For conciseness, these examples create their content scripts as strings and use the contentScript property. In your own add-on, you will probably want to create your content scripts in separate files and pass their URLs using the contentScriptFile property. See Working with Content Scripts for more information.

-
-

Unless your content script is extremely simple and consists only of a static string, don't use contentScript: if you do, you may have problems getting your add-on approved on AMO.

-

Instead, keep the script in a separate file and load it using contentScriptFile. This makes your code easier to maintain, secure, debug and review.

-
-

Show an "Edit Page Source" item when the user right-clicks a non-interactive part of the page:

-
require("sdk/context-menu").Item({
-  label: "Edit Page Source",
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  self.postMessage(document.URL);' +
-                 '});',
-  onMessage: function (pageURL) {
-    editSource(pageURL);
-  }
-});
-

Show an "Edit Image" item when the menu is invoked on an image:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "Edit Image",
-  context: cm.SelectorContext("img"),
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  self.postMessage(node.src);' +
-                 '});',
-  onMessage: function (imgSrc) {
-    openImageEditor(imgSrc);
-  }
-});
-

Show an "Edit Mozilla Image" item when the menu is invoked on an image in a mozilla.org or mozilla.com page:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "Edit Mozilla Image",
-  context: [
-    cm.URLContext(["*.mozilla.org", "*.mozilla.com"]),
-    cm.SelectorContext("img")
-  ],
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  self.postMessage(node.src);' +
-                 '});',
-  onMessage: function (imgSrc) {
-    openImageEditor(imgSrc);
-  }
-});
-

Show an "Edit Page Images" item when the page contains at least one image:

-
var cm = require("sdk/context-menu");
-cm.Item({
-  label: "Edit Page Images",
-  // This ensures the item only appears during the page context.
-  context: cm.PageContext(),
-  contentScript: 'self.on("context", function (node) {' +
-                 '  var pageHasImgs = !!document.querySelector("img");' +
-                 '  return pageHasImgs;' +
-                 '});' +
-                 'self.on("click", function (node, data) {' +
-                 '  var imgs = document.querySelectorAll("img");' +
-                 '  var imgSrcs = [];' +
-                 '  for (var i = 0 ; i < imgs.length; i++)' +
-                 '    imgSrcs.push(imgs[i].src);' +
-                 '  self.postMessage(imgSrcs);' +
-                 '});',
-  onMessage: function (imgSrcs) {
-    openImageEditor(imgSrcs);
-  }
-});
-

Show a "Search With" menu when the user right-clicks an anchor that searches Google or Wikipedia with the text contained in the anchor:

-
var cm = require("sdk/context-menu");
-var googleItem = cm.Item({
-  label: "Google",
-  data: "http://www.google.com/search?q="
-});
-var wikipediaItem = cm.Item({
-  label: "Wikipedia",
-  data: "http://en.wikipedia.org/wiki/Special:Search?search="
-});
-var searchMenu = cm.Menu({
-  label: "Search With",
-  context: cm.SelectorContext("a[href]"),
-  contentScript: 'self.on("click", function (node, data) {' +
-                 '  var searchURL = data + node.textContent;' +
-                 '  window.location.href = searchURL;' +
-                 '});',
-  items: [googleItem, wikipediaItem]
-});
-

Globals

-

Constructors

-

Item(options)

-

Creates a labeled menu item that can perform an action when clicked.

-
Parameters
-

options : object
- Required options:

- - - - - - - - - - - - - - - -
NameType 
labelstring -

The item's label. It must either be a string or an object that implements toString().

-
-

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
imagestring -

The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI.

-
datastring -

An optional arbitrary value to associate with the item. It must be either a string or an object that implements toString(). It will be passed to click listeners.

-
contextvalue -

If the item is contained in the top-level context menu, this declaratively specifies the context under which the item will appear; see Specifying Contexts above.

-
contentScriptstring,array -

If the item is contained in the top-level context menu, this is the content script or an array of content scripts that the item can use to interact with the page.

-
contentScriptFilestring,array -

If the item is contained in the top-level context menu, this is the local file URL of the content script or an array of such URLs that the item can use to interact with the page.

-
onMessagefunction -

If the item is contained in the top-level context menu, this function will be called when the content script calls self.postMessage. It will be passed the data that was passed to postMessage.

-
- -

Creates a labeled menu item that expands into a submenu.

-
Parameters
-

options : object
- Required options:

- - - - - - - - - - - - - - - - - - - - -
NameType 
labelstring -

The item's label. It must either be a string or an object that implements toString().

-
itemsarray -

An array of menu items that the menu will contain. Each must be an Item, Menu, or Separator.

-
-

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
imagestring -

The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI.

-
contextvalue -

If the menu is contained in the top-level context menu, this declaratively specifies the context under which the menu will appear; see Specifying Contexts above.

-
contentScriptstring,array -

If the menu is contained in the top-level context menu, this is the content script or an array of content scripts that the menu can use to interact with the page.

-
contentScriptFilestring,array -

If the menu is contained in the top-level context menu, this is the local file URL of the content script or an array of such URLs that the menu can use to interact with the page.

-
onMessagefunction -

If the menu is contained in the top-level context menu, this function will be called when the content script calls self.postMessage. It will be passed the data that was passed to postMessage.

-
-

Separator()

-

Creates a menu separator.

-

PageContext()

-

Creates a page context. See Specifying Contexts above.

-

SelectionContext()

-

Creates a context that occurs when a page contains a selection. See Specifying Contexts above.

-

SelectorContext(selector)

-

Creates a context that matches a given CSS selector. See Specifying Contexts above.

-
Parameters
-

selector : string
- A CSS selector.

-

URLContext(matchPattern)

-

Creates a context that matches pages with particular URLs. See Specifying Contexts above.

-
Parameters
-

matchPattern : string,array
- A match pattern string, regexp or an array of match pattern strings or regexps.

-

PredicateContext(predicateFunction)

-
-

New in Firefox 29

-
-

Creates a context that occurs when predicateFunction returns a true value. See Specifying Contexts above.

-
Parameters
-

predicateFunction : function(context)
- A function which will be called with an object argument that provide information about the invocation context. context object properties:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
documentTypeThe MIME type of the document the menu was invoked in. E.g. text/html for HTML pages, application/xhtml+xml for XHTML, or image/jpeg if viewing an image directly.
documentURLThe URL of the document the menu was invoked in.
targetNameThe name of the DOM element that the menu was invoked on, in lower-case.
targetIDThe id attribute of the element that the menu was invoked on, or null if not set.
isEditabletrue if the menu was invoked in an editable element, and that element isn't disabled or read-only.  This includes non-input elements with the contenteditable attribute set to true.
selectionTextThe current selection as a text string, or null. If the menu was invoked in an input text box or area, this is the selection of that element, otherwise the selection in the contents of the window.
srcURLThe src URL of the element that the menu was invoked on, or null if it doesn't have one.
linkURLThe href URL of the element that the menu was invoked on, or null if it doesn't have one.
valueThe current contents of a input text box or area if the menu was invoked in one, null otherwise.
-

Item

-

A labeled menu item that can perform an action when clicked.

-

Methods

-

destroy()

-

Permanently removes the item from its parent menu and frees its resources. The item must not be used afterward. If you need to remove the item from its parent menu but use it afterward, call removeItem() on the parent menu instead.

-

Properties

-

label

-

The menu item's label. You can set this after creating the item to update its label later.

-

image

-

The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. You can set this after creating the item to update its image later. To remove the item's image, set it to null.

-

data

-

An optional arbitrary value to associate with the item. It must be either a string or an object that implements toString(). It will be passed to click listeners. You can set this after creating the item to update its data later.

-

context

-

A list of declarative contexts for which the menu item will appear in the context menu. Contexts can be added by calling context.add() and removed by called context.remove().

-

parentMenu

-

The item's parent Menu, or null if the item is contained in the top-level context menu. This property is read-only. To add the item to a new menu, call that menu's addItem() method.

-

contentScript

-

The content script or the array of content scripts associated with the menu item during creation.

-

contentScriptFile

-

The URL of a content script or the array of such URLs associated with the menu item during creation.

-

Events

-

message

-

If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event.

-
Arguments
-

value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value.

- -

A labeled menu item that expands into a submenu.

-

Methods

-

addItem(item)

-

Appends a menu item to the end of the menu. If the item is already contained in another menu or in the top-level context menu, it's automatically removed first. If the item is already contained in this menu it will just be moved to the end of the menu.

-
Parameters
-

item : Item,Menu,Separator
- The Item, Menu, or Separator to add to the menu.

-

removeItem(item)

-

Removes the given menu item from the menu. If the menu does not contain the item, this method does nothing.

-
Parameters
-

item : Item,Menu,Separator
- The menu item to remove from the menu.

-

destroy()

-

Permanently removes the menu from its parent menu and frees its resources. The menu must not be used afterward. If you need to remove the menu from its parent menu but use it afterward, call removeItem() on the parent menu instead.

-

Properties

-

label

-

The menu's label. You can set this after creating the menu to update its label later.

-

items

-

An array containing the items in the menu. The array is read-only, meaning that modifications to it will not affect the menu. However, setting this property to a new array will replace all the items currently in the menu with the items in the new array.

-

image

-

The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's data directory, or a data URI. You can set this after creating the menu to update its image later. To remove the menu's image, set it to null.

-

context

-

A list of declarative contexts for which the menu will appear in the context menu. Contexts can be added by calling context.add() and removed by called context.remove().

-

parentMenu

-

The menu's parent Menu, or null if the menu is contained in the top-level context menu. This property is read-only. To add the menu to a new menu, call that menu's addItem() method.

-

contentScript

-

The content script or the array of content scripts associated with the menu during creation.

-

contentScriptFile

-

The URL of a content script or the array of such URLs associated with the menu during creation.

-

Events

-

message

-

If you listen to this event you can receive message events from content scripts associated with this menu item. When a content script posts a message using self.postMessage(), the message is delivered to the add-on code in the menu item's message event.

-
Arguments
-

value : Listeners are passed a single argument which is the message posted from the content script. The message can be any JSON-serializable value.

-

Separator

-

A menu separator. Separators can be contained only in Menus, not in the top-level context menu.

-

Methods

-

destroy()

-

Permanently removes the separator from its parent menu and frees its resources. The separator must not be used afterward. If you need to remove the separator from its parent menu but use it afterward, call removeItem() on the parent menu instead.

-

Properties

-

parentMenu

-

The separator's parent Menu. This property is read-only. To add the separator to a new menu, call that menu's addItem() method.

diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html deleted file mode 100644 index 32b39d045b..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: High-Level APIs -slug: Mozilla/Add-ons/SDK/High-Level_APIs -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs ---- -

Modules listed on this page implement high-level APIs for building add-ons: creating user interfaces, interacting with the web, and interacting with the browser.

-

Unless the documentation explicitly says otherwise, all these modules are "Stable": we'll avoid making incompatible changes to them. {{ LandingPageListSubpages ("/en-US/Add-ons/SDK/High-Level_APIs", 5) }}

diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html deleted file mode 100644 index 535385e895..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html +++ /dev/null @@ -1,525 +0,0 @@ ---- -title: passwords -slug: Mozilla/Add-ons/SDK/High-Level_APIs/passwords -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/passwords ---- -
-

Stable

-
-

Interact with Firefox's Password Manager to add, retrieve and remove stored credentials.

-

Usage

-

A credential is the set of information a user supplies to authenticate herself with a service. Typically a credential consists of a username and a password.

-

Using this module you can:

-
    -
  1. -

    Search for credentials which have been stored in the Password Manager. You can then use the credentials to access their related service (for example, by logging into a web site).

    -
  2. -
  3. -

    Store credentials in the Password Manager. You can store different sorts of credentials, as outlined in the "Credentials" section below.

    -
  4. -
  5. -

    Remove stored credentials from the Password Manager.

    -
  6. -
-

Credentials

-

In this API, credentials are represented by objects.

-

You create credential objects to pass into the API, and the API also returns credential objects to you. The sections below explain both the properties you should define on credential objects and the properties you can expect on credential objects returned by the API.

-

All credential objects include username and password properties. Different sorts of stored credentials include various additional properties, as outlined in this section.

-

You can use the Passwords API with three sorts of credentials:

- -

Add-on Credential

-

These are associated with your add-on rather than a particular web site. They contain the following properties:

- - - - - - - - - - - - - - - - - - - - - - -
usernameThe username.
passwordThe password.
url -

For an add-on credential, this property is of the form:
- addon:<addon-id>, where <addon-id> is the add-on's Program ID.

-

You don't supply this value when storing an add-on credential: it is automatically generated for you. However, you can use it to work out which stored credentials belong to your add-on by comparing it with the uri property of the self module.

-
realm -

You can use this as a name for the credential, to distinguish it from any other credentials you've stored.

-

The realm is displayed in Firefox's Password Manager, under "Site", in brackets after the URL. For example, if the realm for a credential is "User Registration", then its "Site" field will look something like:

- addon:jid0-01mBBFyu0ZAXCFuB1JYKooSTKIc (User Registration)
-

HTML Form Credential

-

If a web service uses HTML forms to authenticate its users, then the corresponding credential is an HTML Form credential.

-

It contains the following properties:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
usernameThe username.
passwordThe password.
urlThe URL for the web service which requires the credential. You should omit anything after the hostname and (optional) port.
formSubmitURLThe value of the form's "action" attribute. You should omit anything after the hostname and (optional) port. If the form doesn't contain an "action" attribute, this property should match the url property.
usernameFieldThe value of the "name" attribute for the form's username field.
passwordFieldThe value of the "name" attribute for the form's password field.
-

So: given a form at http://www.example.com/login with the following HTML:

-
<form action="http://login.example.com/foo/authenticate.cgi">
-      <div>Please log in.</div>
-      <label>Username:</label> <input type="text" name="uname">
-      <label>Password:</label> <input type="password" name="pword">
-</form>
-

The corresponding values for the credential (excluding username and password) should be:

-
  url: "http://www.example.com"
-  formSubmitURL: "http://login.example.com"
-  usernameField: "uname"
-  passwordField: "pword"
-
-

Note that for both url and formSubmitURL, the portion of the URL after the hostname is omitted.

-

HTTP Authentication Credential

-

These are used to authenticate the user to a web site which uses HTTP Authentication, as detailed in RFC 2617. They contain the following properties:

- - - - - - - - - - - - - - - - - - - - - - -
usernameThe username.
passwordThe password.
urlThe URL for the web service which requires the credential. You should omit anything after the hostname and (optional) port.
realm -

The WWW-Authenticate response header sent by the server may include a "realm" field as detailed in RFC 2617. If it does, this property contains the value for the "realm" field. Otherwise, it is omitted.

-

The realm is displayed in Firefox's Password Manager, under "Site", in brackets after the URL.

-
-

So: if a web server at http://www.example.com requested authentication with a response code like this:

-
  HTTP/1.0 401 Authorization Required
-  Server: Apache/1.3.27
-  WWW-Authenticate: Basic realm="ExampleCo Login"
-
-

The corresponding values for the credential (excluding username and password) should be:

-
  url: "http://www.example.com"
-  realm: "ExampleCo Login"
-
-

onComplete and onError

-

This API is explicitly asynchronous, so all its functions take two callback functions as additional options: onComplete and onError.

-

onComplete is called when the operation has completed successfully and onError is called when the function encounters an error.

-

Because the search function is expected to return a list of matching credentials, its onComplete option is mandatory. Because the other functions don't return a value in case of success their onComplete options are optional.

-

For all functions, onError is optional.

-

Globals

-

Functions

-

search(options)

-

This function is used to retrieve a credential, or a list of credentials, stored in the Password Manager.

-

You pass it any subset of the possible properties a credential can contain. Credentials which match all the properties you supplied are returned as an argument to the onComplete callback.

-

So if you pass in an empty set of properties, all stored credentials are returned:

-
function show_all_passwords() {
-  require("sdk/passwords").search({
-    onComplete: function onComplete(credentials) {
-      credentials.forEach(function(credential) {
-        console.log(credential.username);
-        console.log(credential.password);
-        });
-      }
-    });
-  }
-

If you pass it a single property, only credentials matching that property are returned:

-
function show_passwords_for_joe() {
-  require("sdk/passwords").search({
-    username: "joe",
-    onComplete: function onComplete(credentials) {
-      credentials.forEach(function(credential) {
-        console.log(credential.username);
-        console.log(credential.password);
-        });
-      }
-    });
-  }
-

If you pass more than one property, returned credentials must match all of them:

-
function show_google_password_for_joe() {
-  require("sdk/passwords").search({
-    username: "joe",
-    url: "https://www.google.com",
-    onComplete: function onComplete(credentials) {
-      credentials.forEach(function(credential) {
-        console.log(credential.username);
-        console.log(credential.password);
-        });
-      }
-    });
-  }
-

To retrieve only credentials associated with your add-on, use the url property, initialized from self.uri:

-
function show_my_addon_passwords() {
-  require("sdk/passwords").search({
-    url: require("sdk/self").uri,
-    onComplete: function onComplete(credentials) {
-      credentials.forEach(function(credential) {
-        console.log(credential.username);
-        console.log(credential.password);
-        });
-      }
-    });
-  }
-
Parameters
-

options : object
- Required options:

- - - - - - - - - - - - - - - -
NameType 
onCompletefunction -

The callback function that is called once the function completes successfully. It is passed all the matching credentials as a list. This is the only mandatory option.

-
-

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
usernamestring -

The username for the credential.

-
passwordstring -

The password for the credential.

-
urlstring -

The URL associated with the credential.

-
formSubmitURLstring -

The URL an HTML form credential is submitted to.

-
realmstring -

For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.

-
usernameFieldstring -

The value of the name attribute for the user name input field in a form.

-
passwordFieldstring -

The value of the name attribute for the password input field in a form.

-
onErrorfunction -

The callback function that is called if the function failed. The callback is passed an error containing a reason of a failure: this is an nsIException object.

-
-

store(options)

-

This function is used to store a credential in the Password Manager.

-

It takes an options object as an argument: this contains all the properties for the new credential.

-

As different sorts of credentials contain different properties, the appropriate options differ depending on the sort of credential being stored.

-

To store an add-on credential:

-
require("sdk/passwords").store({
-  realm: "User Registration",
-  username: "joe",
-  password: "SeCrEt123",
-});
-

To store an HTML form credential:

-
require("sdk/passwords").store({
-  url: "http://www.example.com",
-  formSubmitURL: "http://login.example.com",
-  username: "joe",
-  usernameField: "uname",
-  password: "SeCrEt123",
-  passwordField: "pword"
-});
-

To store an HTTP Authentication credential:

-
require("sdk/passwords").store({
-  url: "http://www.example.com",
-  realm: "ExampleCo Login",
-  username: "joe",
-  password: "SeCrEt123",
-});
-

See "Credentials" above for more details on how to set these properties.

-

The options parameter may also include onComplete and onError callback functions, which are called when the function has completed successfully and when it encounters an error, respectively. These options are both optional.

-
Parameters
-

options : object
- Required options:

- - - - - - - - - - - - - - - - - - - - -
NameType 
usernamestring -

The username for the credential.

-
passwordstring -

The password for the credential.

-
-

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
urlstring -

The URL to which the credential applies. Omitted for add-on credentials.

-
formSubmitURLstring -

The URL a form-based credential was submitted to. Omitted for add-on credentials and HTTP Authentication credentials.

-
realmstring -

For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.

-
usernameFieldstring -

The value of the name attribute for the username input in a form. Omitted for add-on credentials and HTTP Authentication credentials.

-
passwordFieldstring -

The value of the name attribute for the password input in a form. Omitted for add-on credentials and HTTP Authentication credentials.

-
onCompletefunction -

The callback function that is called once the function completes successfully.

-
onErrorfunction -

The callback function that is called if the function failed. The callback is passed an error argument: this is an nsIException object.

-
-

remove(options)

-

Removes a stored credential. You supply it all the properties of the credential to remove, along with optional onComplete and onError callbacks.

-

Because you must supply all the credential's properties, it may be convenient to call search first, and use its output as the input to remove. For example, to remove all of joe's stored credentials:

-
require("sdk/passwords").search({
-  username: "joe",
-  onComplete: function onComplete(credentials) {
-    credentials.forEach(require("sdk/passwords").remove);
-  })
-});
-

To change an existing credential just call store after remove succeeds:

-
require("sdk/passwords").remove({
-  realm: "User Registration",
-  username: "joe",
-  password: "SeCrEt123"
-  onComplete: function onComplete() {
-    require("sdk/passwords").store({
-      realm: "User Registration",
-      username: "joe",
-      password: "{new password}"
-    })
-  }
-});
-
Parameters
-

options : object
- Required options:

- - - - - - - - - - - - - - - - - - - - -
NameType 
usernamestring -

The username for the credential.

-
passwordstring -

The password for the credential.

-
-

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
urlstring -

The URL to which the credential applies. Omitted for add-on credentials.

-
formSubmitURLstring -

The URL a form-based credential was submitted to. Omitted for add-on credentials and HTTP Authentication credentials.

-
realmstring -

For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.

-
usernameFieldstring -

The value of the name attribute for the username input in a form. Omitted for add-on credentials and HTTP Authentication credentials.

-
passwordFieldstring -

The value of the name attribute for the password input in a form. Omitted for add-on credentials and HTTP Authentication credentials.

-
onCompletefunction -

The callback function that is called once the function has completed successfully.

-
onErrorfunction -

The callback function that is called if the function failed. The callback is passed an error argument: this is an nsIException object.

-
-

 

diff --git a/files/ru/mozilla/add-ons/sdk/index.html b/files/ru/mozilla/add-ons/sdk/index.html deleted file mode 100644 index 6c8217da66..0000000000 --- a/files/ru/mozilla/add-ons/sdk/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Add-on SDK -slug: Mozilla/Add-ons/SDK -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK ---- -

C помощью  SDK вы можете создавать дополнения для Firefox , используя стандартные веб-технологии: JavaScript, HTML, CSS. SDK включает в себя API-интерфейсы JavaScript, которые можно использовать для создания дополнений и инструменты для создания, запуска, тестирования и упаковки дополнений.

- -
-

Учебники

- -
- - -
-
-
Создание компонентов пользовательского интерфейса
-
Создание компонентов пользовательского интерфейса, такие как кнопки панели инструментов , контекстные меню, пункты меню, и диалоговые окна.
-
Изменение веб-страниц
-
Изменение страниц, которые соответствуют заданному URL шаблону или динамически изменить заданную вкладку.
-
Соединяем всё вместе
-
Обучение на примере расширения Комментатор.
-
-
-
- -
-

Инструкции

- -
-
-
-
Руководство для разработчика НРП
-
Learn how to start contributing to the SDK, and about the most important idioms used in the SDK code, such as modules, classes and inheritance, private properties, and content processes.
-
НРП инфраструктура
-
Aspects of the SDK's underlying technology: modules, the Program ID, and the rules defining Firefox compatibility.
-
Скрипты содержимого
-
A detailed guide to working with content scripts.
-
-
- - -
- -
-

Справочник

- -
-
-
-
Высокоуровневый ИПП
-
Справочная документация для высокоуровневого ИПП в НРП.
-
Справочник программ
-
Справочная документация для cfx программы используемая для разработки, тестирования, и упаковывания расширений, глобальная console используемая для протоколирования, и файл package.json.
-
-
- -
-
-
Низкоуровневый ИПП
-
Справочная документация для низкоуровневого ИПП в НРП.
-
-
-
- -

 

- - diff --git a/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html b/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html deleted file mode 100644 index 8cd08458f0..0000000000 --- a/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Low-Level APIs -slug: Mozilla/Add-ons/SDK/Low-Level_APIs -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs ---- -

Modules in this section implement low-level APIs. These modules fall roughly into three categories:

- -

These modules are still in active development, and we expect to make incompatible changes to them in future releases.

-

{{ LandingPageListSubpages ("/en-US/Add-ons/SDK/Low-Level_APIs", 5) }}

-

 

diff --git a/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html b/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html deleted file mode 100644 index 299e234fb2..0000000000 --- a/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html +++ /dev/null @@ -1,595 +0,0 @@ ---- -title: places/bookmarks -slug: Mozilla/Add-ons/SDK/Low-Level_APIs/places_bookmarks -translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/places_bookmarks ---- -
-

Unstable

-
- -

Создание, изменение и удаление закладок.

- -

Usage

- -

Этот модуль экспортирует:

- - - -

save() и search() асинхронные функции: they synchronously return a PlacesEmitter object, which then asynchronously emits events as the operation progresses and completes.

- -

Each retrieved bookmark item represents only a snapshot of state at a specific time. The module does not automatically sync up a Bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user.

- -

Примеры

- -

Создание новой закладки

- -
let { Bookmark, save } = require("sdk/places/bookmarks");
-
-// Create a new bookmark instance, unsaved
-let bookmark = Bookmark({ title: "Mozilla", url: "http://mozilla.org" });
-
-// Attempt to save the bookmark instance to the Bookmarks database
-// and store the emitter
-let emitter = save(bookmark);
-
-// Listen for events
-emitter.on("data", function (saved, inputItem) {
-  // on a "data" event, an item has been updated, passing in the
-  // latest snapshot from the server as `saved` (with properties
-  // such as `updated` and `id`), as well as the initial input
-  // item as `inputItem`
-  console.log(saved.title === inputItem.title); // true
-  console.log(saved !== inputItem); // true
-  console.log(inputItem === bookmark); // true
-}).on("end", function (savedItems, inputItems) {
-  // Similar to "data" events, except "end" is an aggregate of
-  // all progress events, with ordered arrays as `savedItems`
-  // and `inputItems`
-});
- -

Создание нескольких закладок в группе

- -
let { Bookmark, Group, save } = require("sdk/places/bookmarks");
-
-let group = Group({ title: "Guitars" });
-let bookmarks = [
-  Bookmark({ title: "Ran", url: "http://ranguitars.com", group: group }),
-  Bookmark({ title: "Ibanez", url: "http://ibanez.com", group: group }),
-  Bookmark({ title: "ESP", url: "http://espguitars.com", group: group })
-];
-
-// Save `bookmarks` array -- notice we don't have `group` in the array,
-// although it needs to be saved since all bookmarks are children
-// of `group`. This will be saved implicitly.
-
-save(bookmarks).on("data", function (saved, input) {
-  // A data event is called once for each item saved, as well
-  // as implicit items, like `group`
-  console.log(input === group || ~bookmarks.indexOf(input)); // true
-}).on("end", function (saves, inputs) {
-  // like the previous example, the "end" event returns an
-  // array of all of our updated saves. Only explicitly saved
-  // items are returned in this array -- the `group` won't be
-  // present here.
-  console.log(saves[0].title); // "Ran"
-  console.log(saves[2].group.title); // "Guitars"
-});
- -

Поиск закладок

- -

Bookmarks can be queried with the search() function, which accepts a query object or an array of query objects, as well as a query options object. Query properties are AND'd together within a single query object, but are OR'd together across multiple query objects.

- -
let { search, UNSORTED } = require("sdk/places/bookmarks");
-
-// Simple query with one object
-search(
-  { query: "firefox" },
-  { sort: "title" }
-).on(end, function (results) {
-  // results matching any bookmark that has "firefox"
-  // in its URL, title or tag, sorted by title
-});
-
-// Multiple queries are OR'd together
-search(
-  [{ query: "firefox" }, { group: UNSORTED, tags: ["mozilla"] }],
-  { sort: "title" }
-).on("end", function (results) {
-  // Our first query is the same as the simple query above;
-  // all of those results are also returned here. Since multiple
-  // queries are OR'd together, we also get bookmarks that
-  // match the second query. The second query's properties
-  // are AND'd together, so results that are in the platform's unsorted
-  // bookmarks folder, AND are also tagged with 'mozilla', get returned
-  // as well in this query
-});
- -

Globals

- -

Constructors

- -

Bookmark(options)

- -

Creates an unsaved bookmark instance.

- -
Parameters
- -

options : object
- Required options:

- - - - - - - - - - - - - - - - - - - - - -
NameType 
titlestring -

The title for the bookmark. Required.

-
urlstring -

The URL for the bookmark. Required.

-
- -

Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
groupGroup -

The parent group that the bookmark lives under. Defaults to the Bookmarks.UNSORTED group.

-
indexnumber -

The index of the bookmark within its group. Last item within the group by default.

-
tagsset -

A set of tags to be applied to the bookmark.

-
- -

Group(options)

- -

Creates an unsaved bookmark group instance.

- -
Parameters
- -

options : object
- Required options:

- - - - - - - - - - - - - - - - -
NameType 
titlestring -

The title for the group. Required.

-
- -

Optional options:

- - - - - - - - - - - - - - - - - - - - - -
NameType 
groupGroup -

The parent group that the bookmark group lives under. Defaults to the Bookmarks.UNSORTED group.

-
indexnumber -

The index of the bookmark group within its parent group. Last item within the group by default.

-
- -

Separator(options)

- -

Creates an unsaved bookmark separator instance.

- -
Parameters
- -

options : object
- Optional options:

- - - - - - - - - - - - - - - - - - - - - -
NameType 
groupGroup -

The parent group that the bookmark group lives under. Defaults to the Bookmarks.UNSORTED group.

-
indexnumber -

The index of the bookmark group within its parent group. Last item within the group by default.

-
- -

Functions

- -

save(bookmarkItems, options)

- -

Creating, saving, and deleting bookmarks are all done with the save() function. This function takes in any of:

- - - -

All of the items passed in are pushed to the platform and are either created, updated or deleted.

- - - -

The function returns a PlacesEmitter that emits a data event for each item as it is saved, and an end event when all items have been saved.

- -
let { Bookmark, Group } = require("sdk/places/bookmarks");
-
-let myGroup = Group({ title: "My Group" });
-let myBookmark = Bookmark({
-  title: "Moz",
-  url: "http://mozilla.com",
-  group: myGroup
-});
-
-save(myBookmark).on("data", function (item, inputItem) {
-  // The `data` event returns the latest snapshot from the
-  // host, so this is a new instance of the bookmark item,
-  // where `item !== myBookmark`. To match it with the input item,
-  // use the second argument, so `inputItem === myBookmark`
-
-  // All explicitly saved items have data events called, as
-  // well as implicitly saved items. In this case,
-  // `myGroup` has to be saved before `myBookmark`, since
-  // `myBookmark` is a child of `myGroup`. `myGroup` will
-  // also have a `data` event called for it.
-}).on("end", function (items, inputItems) {
-  // The `end` event returns all items that are explicitly
-  // saved. So `myGroup` will not be in this array,
-  // but `myBookmark` will be.
-  // `inputItems` matches the initial input as an array,
-  // so `inputItems[0] === myBookmark`
-});
-
-// Saving multiple bookmarks, as duck-types in this case
-
-let bookmarks = [
-  { title: "mozilla", url: "http://mozilla.org", type: "bookmark" },
-  { title: "firefox", url: "http://firefox.com", type: "bookmark" },
-  { title: "twitter", url: "http://twitter.com", type: "bookmark" }
-];
-
-save(bookmarks).on("data", function (item, inputItem) {
-  // Each item in `bookmarks` has its own `data` event
-}).on("end", function (results, inputResults) {
-  // `results` is an array of items saved in the same order
-  // as they were passed in.
-});
- -
Parameters
- -

bookmarkItems : bookmark|group|separator|array
- A bookmark item (Bookmark, Group, Separator), or an array of bookmark items to be saved.

- -

options : object
- Optional options:

- - - - - - - - - - - - - - - - -
NameType 
resolvefunction -

A resolution function that is invoked during an attempt to save a bookmark item that is not derived from the latest state from the platform. Invoked with two arguments, mine and platform, where mine is the item that is being saved, and platform is the current state of the item on the item. The object returned from this function is what is saved on the platform. By default, all changes on an outdated bookmark item overwrite the platform's bookmark item.

-
- -
Returns
- -

PlacesEmitter : Returns a PlacesEmitter.

- -

remove(items)

- -

A helper function that takes in a bookmark item, or an Array of several bookmark items, and sets each item's remove property to true. This does not remove the bookmark item from the database: it must be subsequently saved.

- -
let { search, save, remove } = require("sdk/places/bookmarks");
-
-search({ tags: ["php"] }).on("end", function (results) {
-  // The search returns us all bookmark items that are
-  // tagged with `"php"`.
-
-  // We then pass `results` into the remove function to mark
-  // all items to be removed, which returns the new modified `Array`
-  // of items, which is passed into save.
-  save(remove(results)).on("end", function (results) {
-    // items tagged with `"php"` are now removed!
-  });
-})
- -
Parameters
- -

items : Bookmark|Group|Separator|array
- A bookmark item, or Array of bookmark items to be transformed to set their remove property to true.

- -
Returns
- -

array : An array of the transformed bookmark items.

- -

search(queries, options)

- -

Queries can be performed on bookmark items by passing in one or more query objects, each of which is given one or more properties.

- -

Within each query object, the properties are AND'd together: so only objects matching all properties are retrieved. Across query objects, the results are OR'd together, meaning that if an item matches any of the query objects, it will be retrieved.

- -

For example, suppose we called search() with two query objects:

- -
[{ url: "mozilla.org", tags: ["mobile"]},
-{ tags: ["firefox-os"]}]
- -

This will return:

- - - -

An options object may be used to determine overall settings such as sort order and how many objects should be returned.

- -
Parameters
- -

queries : object|array
- An Object representing a query, or an Array of Objects representing queries. Each query object can take several properties, which are queried against the bookmarks database. Each property is AND'd together, meaning that bookmarks must match each property within a query object. Multiple query objects are then OR'd together.

- -

options : object
- Optional options:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
NameType 
countnumber -

The number of bookmark items to return. If left undefined, no limit is set.

-
sortstring -

A string specifying how the results should be sorted. Possible options are 'title', 'date', 'url', 'visitCount', 'dateAdded' and 'lastModified'.

-
descendingboolean -

A boolean specifying whether the results should be in descending order. By default, results are in ascending order.

-
- -

Properties

- - - -

This is a constant, default Group on the Firefox platform, the Bookmarks Menu. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.

- -

TOOLBAR

- -

This is a constant, default Group on the Firefox platform, the Bookmarks Toolbar. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.

- -

UNSORTED

- -

This is a constant, default Group on the Firefox platform, the Unsorted Bookmarks group. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.

- -

Bookmark

- -

Properties

- -

title

- -

The bookmark's title.

- -

url

- -

The bookmark's URL.

- -

group

- -

The group instance that the bookmark lives under.

- -

index

- -

The index of the bookmark within its group.

- -

updated

- -

A Unix timestamp indicating when the bookmark was last updated on the platform.

- -

tags

- -

A Set of tags that the bookmark is tagged with.

- -

Group

- -

Properties

- -

title

- -

The bookmark group's title.

- -

group

- -

The group instance that the bookmark group lives under.

- -

index

- -

The index of the bookmark group within its group.

- -

updated

- -

A Unix timestamp indicating when the bookmark was last updated on the platform.

- -

Separator

- -

Properties

- -

group

- -

The group instance that the bookmark group lives under.

- -

index

- -

The index of the bookmark group within its group.

- -

updated

- -

A Unix timestamp indicating when the bookmark was last updated on the platform.

- -

PlacesEmitter

- -

The PlacesEmitter is not exported from the module, but returned from the save and search functions. The PlacesEmitter inherits from event/target, and emits data, error, and end.

- -

data events are emitted for every individual operation (such as: each item saved, or each item found by a search query), whereas end events are emitted as the aggregate of an operation, passing an array of objects into the handler.

- -

Events

- -

data

- -

The data event is emitted when a bookmark item that was passed into the save method has been saved to the platform. This includes implicit saves that are dependencies of the explicit items saved. For example, when creating a new bookmark group with two bookmark items as its children, and explicitly saving the two bookmark children, the unsaved parent group will also emit a data event.

- -
let { Bookmark, Group, save } = require("sdk/places/bookmarks");
-
-let group = Group({ title: "my group" });
-let bookmarks = [
-  Bookmark({ title: "mozilla", url: "http://mozilla.com", group: group }),
-  Bookmark({ title: "w3", url: "http://w3.org", group: group })
-];
-
-save(bookmarks).on("data", function (item) {
-  // This function will be called three times:
-  // once for each bookmark saved
-  // once for the new group specified implicitly
-  // as the parent of the two items
-});
- -

The data event is also called for search requests, with each result being passed individually into its own data event.

- -
let { search } = require("sdk/places/bookmarks");
-
-search({ query: "firefox" }).on("data", function (item) {
-  // each bookmark item that matches the query will
-  // be called in this function
-});
- -
Arguments
- -

Bookmark|Group|Separator : For the save function, this is the saved, latest snapshot of the bookmark item. For search, this is a snapshot of a bookmark returned from the search query.

- -

Bookmark|Group|Separator|object : Only in save data events. The initial instance of the item that was used for the save request.

- -

error

- -

The error event is emitted whenever a bookmark item's save could not be completed.

- -
Arguments
- -

string : A string indicating the error that occurred.

- -

Bookmark|Group|Separator|object : Only in save error events. The initial instance of the item that was used for the save request.

- -

end

- -

The end event is called when all bookmark items and dependencies have been saved, or an aggregate of all items returned from a search query.

- -
Arguments
- -

array : The array is an ordered list of the input bookmark items, replaced with their updated, latest snapshot instances (the first argument in the data handler), or in the case of an error, the initial instance of the item that was used for the save request (the second argument in the data or error handler).

diff --git a/files/ru/mozilla/add-ons/sdk/tools/console/index.html b/files/ru/mozilla/add-ons/sdk/tools/console/index.html deleted file mode 100644 index d28b31d127..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/console/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: console -slug: Mozilla/Add-ons/SDK/Tools/console -translation_of: Archive/Add-ons/Add-on_SDK/Tools/console ---- -

Enables your add-on to log error, warning or informational messages. If you have started Firefox for your add-on from the command line with cfx run or cfx test then these messages appear in the command shell you used. If the add-on has been installed in Firefox, then the messages appear in the Browser Console.

-

If you're developing your add-on using the Extension Auto-installer, then the add-on is installed in Firefox, meaning that messages will appear in the Browser Console. But see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations.

-

Console Methods

-

All console methods except exception() and trace() accept one or more JavaScript objects as arguments and log them to the console. Depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged.

-

console.debug(object[, object, ...])

-

Logs the arguments to the console, preceded by "debug:" and the name of your add-on:

-
console.debug("This is a debug message");
-
debug: my-addon: This is a debug message
-
-

console.error(object[, object, ...])

-

Logs the arguments to the console, preceded by "error:" and the name of your add-on:

-
console.error("This is an error message");
-
error: my-addon: This is an error message
-
-

console.exception(exception)

-

Logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available.

-
try {
-   doThing();
-} catch (e) {
-   console.exception(e);
-}
-
-function UserException(message) {
-   this.message = message;
-   this.name = "UserException";
-}
-
-function doThing() {
-  throw new UserException("Thing could not be done!");
-}
-
error: my-addon: An exception occurred.
-UserException: Thing could not be done!
-
-

console.info(object[, object, ...])

-

A synonym for console.log().

-

console.log(object[, object, ...])

-

Logs the arguments to the console, preceded by "info:" and the name of your add-on:

-
console.log("This is an informational message");
-
info: my-addon: This is an informational message
-
-

console.time(name)

-

Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.

-

console.timeEnd(name)

-

Stops the specified timer and logs the elapsed time in seconds since its start. See Timers.

-

console.trace()

-

Logs a stack trace at the point the function is called.

-

console.warn(object[, object, ...])

-

Logs the arguments to the console, preceded by "warn:" and the name of your add-on:

-
console.warn("This is a warning message");
-
warn: my-addon: This is a warning message
-
-

Logging Levels

-

Logging's useful, of course, especially during development. But the more logging there is, the more noise you see in the console output. Especially when debug logging shows up in a production environment, the noise can make it harder, not easier, to debug issues.

-

This is the problem that logging levels are designed to fix. The console defines a number of logging levels, from "more verbose" to "less verbose", and a number of different logging functions that correspond to these levels, which are arranged in order of "severity" from informational messages, through warnings, to errors.

-

At a given logging level, only calls to the corresponding functions and functions with a higher severity will have any effect.

-

For example, if the logging level is set to "info", then calls to info(), log(), warn(), and error() will all result in output being written. But if the logging level is "warn" then only calls to warn() and error() have any effect, and calls to info() and log() are simply discarded.

-

This means that the same code can be more verbose in a development environment than in a production environment - you just need to arrange for the appropriate logging level to be set.

-

The complete set of logging levels is given in the table below, along with the set of functions that will result in output at each level:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LevelWill log calls to:
allAny console method
debugdebug(), error(), exception(), info(), log(), time(), timeEnd(), trace(), warn()
infoerror(), exception(), info(), log(), time(), timeEnd(), trace(), warn()
warnerror(), exception(), warn()
errorerror(), exception()
offNothing
-

Setting the Logging Level

-

The logging level defaults to "error".

-

There are two system preferences that can be used to override this default:

- -

Both these preferences can be set programmatically using the preferences/service API, or manually using about:config. The value for each preference is the desired logging level, given as a string.

-

When you run your add-on using cfx run or cfx test, the global extensions.sdk.console.logLevel preference is automatically set to "info". This means that calls to console.log() will appear in the console output.

-

When you install an add-on into Firefox, the logging level will be "error" by default (that is, unless you have set one of the two preferences). This means that messages written using debug(), log(), info(), trace(), and warn() will not appear in the console.

-

This includes add-ons being developed using the Extension Auto-installer.

diff --git a/files/ru/mozilla/add-ons/sdk/tools/index.html b/files/ru/mozilla/add-ons/sdk/tools/index.html deleted file mode 100644 index b55c672f17..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Tools -slug: Mozilla/Add-ons/SDK/Tools -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Tools ---- -

Articles listed here provide a reference for the SDK's tools:

-

{{ LandingPageListSubpages ("/en-US/Add-ons/SDK/Tools", 5) }}

diff --git a/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html b/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html deleted file mode 100644 index dbfacde500..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html +++ /dev/null @@ -1,497 +0,0 @@ ---- -title: jpm -slug: Mozilla/Add-ons/SDK/Tools/jpm -translation_of: Archive/Add-ons/Add-on_SDK/Tools/jpm ---- -
-

Вы можете использовать jpm для Firefox 38 или более поздних версий.

- -

Данный материал относится только для jpm.

-
- -

Это Node-ориентированная замена устаревшего cfx. Позволяет тестировать, запускать и создавать дополнения для Firefox.

- -

Смотри также jpm tutorial.

- -

jpm вызывается через:

- -
jpm [command] [options]
-
- -

jpm поддерживает следующие глобальные опции:

- -
-h, --help        - show a help message and exit
--V, --version     - print the jpm version number
-
- -

Установка

- -

jpm распространяется с помощью менеджера пакетов npm, поэтому чтобы установить jpm, вам необходимо предварительно установить менеджер пакетов npm, если вы этого ещё не сделали. npm входит в Node.js, поэтому чтобы установить npm - посетите nodejs.org и нажмите кнопку INSTALL.

- -

После этого вы можете установить jpm, как и любой другой npm пакет:

- -
npm install jpm -g
- -

В зависимости от настроек и операционной системы, вам может потребоваться запустить его с правами администратора (Linux: Debian, Ubuntu, и т.п.):

- -
sudo npm install jpm -g
- -

После установки введите в командной строке:

- -
jpm
- -

Вы должны увидеть краткое описание доступных команд. Обратите внимание, что в отличие от cfx, jpm доступно из любой запущенной командной строки, в случае, если при установке jpm использовался флаг -g.

- -

Проблемы?

- -

Если у вас возникли проблемы, то обратитесь за помощью. Пользователи SDK и участники проекта готовы обсудить и предложения в project mailing list. Попробуйте поискать там, возможно похожий вопрос уже обсуждался там. Вы также можете обратиться к пользователям SDK в #jetpack на Mozilla's IRC network.

- -

Справочник команд

- -

В jpm доступно шесть команд:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
jpm initСоздать каркас дополнения в качестве отправной точки для создания вашего дополнения.
jpm runЗапустить копию Firefox с установленным дополнением.
jpm testЗапуск тестирования модуля вашего дополнения.
jpm xpiУпаковать дополнение в XPI пакет, формат файла установки для дополнений Firefox.
jpm postУпаковать дополнение в пакет XPI и отправить на URL.
jpm watchpostУпаковывать дополнение в пакет XPI и отправлять на URL при каждом изменении файла.
- -

jpm init

- -

Данная команда инициализирует новое дополнение, с нуля.

- -

Для этого создайте новый каталог, перейдите в него и запустите jpm init.

- -
mkdir my-addon
-cd my-addon
-jpm init
- -

Вам будет предложено указать некоторую информацию о вашем дополнении: данная информация будет использована для создания файла настроек дополнения package.json.

- - - -

Большинство из этих полей имеют значения по умолчанию, который указан в скобках после вопроса. Если вы просто нажмите Enter, то в настройках будет указано значение по умолчанию.

- -

После того как вы укажете значения или выберите значение по умолчанию для этих свойств, вам будет показано полное содержание "package.json" и предложено принять его.

- -

После jpm создаст каркас дополнения в качестве отправной точки для разрабатываемого вами дополнения, со следующей структурой файлов:

- - - -

jpm run

- -

Эта команда запускает новый экземпляр Firefox с подключенным дополнением:

- -
jpm run
- -

jpm run принимает следующие значения:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-b --binary BINARY -

Use the version of Firefox specified in BINARY. BINARY may be specified as a full path or as a path relative to the current directory.

- -
-jpm run -b /path/to/Firefox/Nightly
- See Selecting a browser version.
--binary-args CMDARGS -

Pass extra arguments to Firefox.

- -

For example, to pass the -jsconsole argument to Firefox, which will launch the Browser Console, try the following:

- -
-jpm run --binary-args -jsconsole
- -

To pass multiple arguments, or arguments containing spaces, quote them:

- -
-jpm run --binary-args '-url mzl.la -jsconsole'
-
--debugRun the add-on debugger attached to the add-on.
-o --overload PATH -

Rather than use the SDK modules built into Firefox, use the modules found at PATH. If -o is specified and PATH is omitted, jpm will look for the JETPACK_ROOT environment variable and use its value as the path.

- -

See Overloading the built-in modules for more information.

-
-p --profile= PROFILE -

By default, jpm uses a clean temporary Firefox profile each time you call jpm run. Use the --profile option to instruct jpm to launch Firefox with an existing profile.

- -

The PROFILE value may be a profile name or the path to the profile.

- -

See Using profiles for more information.

-
-v --verboseVerbose operation.
--no-copy -
Use with caution because jpm run|test changes many preferences, never use with your main profile.
- -
This only applies when --profile is used.
- Disables the copying of the profile used, which allows one to reuse a profile.
 
- -

jpm test

- -

Команда запускает тестирование дополнения. Происходит следующее:

- - - -
jpm test
-
- -

See the tutorial on unit testing and the reference documentation for the assert module for more details on this.

- -

jpm test accepts the following options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-b --binary BINARY -

Use the version of Firefox specified in BINARY. BINARY may be specified as a full path or as a path relative to the current directory.

- -
-jpm test -b /path/to/Firefox/Nightly
- -

See Selecting a browser version.

-
--binary-args CMDARGS -

Pass extra arguments to Firefox.

- -

For example, to pass the -jsconsole argument to Firefox, which will launch the Browser Console, try the following:

- -
-jpm test --binary-args -jsconsole
- -

To pass multiple arguments, or arguments containing spaces, quote them:

- -
-jpm test --binary-args '-url mzl.la -jsconsole'
-
--debugRun the add-on debugger attached to the add-on.
-f --filter FILE[:TEST] -

Only run tests whose filenames match FILE and optionally match TEST, both regexps.

- -
-jpm test --filter base64:btoa
- -

The above command only runs tests in files whose names contain "base64", and in those files only runs tests whose names contain "btoa".

-
-o --overload PATH -

Rather than use the SDK modules built into Firefox, use the modules found at PATH. If -o is specified and PATH is omitted, jpm will look for the JETPACK_ROOT environment variable and use its value as the path.

- -

See Overloading the built-in modules for more information.

-
-p --profile PROFILE -

By default, jpm uses a clean temporary Firefox profile each time you call jpm run. Use the --profile option to instruct jpm to launch Firefox with an existing profile.

- -

The PROFILE value may be a profile name or the path to the profile.

- -

See Using profiles for more information.

-
--stop-on-error -

By default jpm test keeps running tests even after tests fail. Specify --stop-on-error to stop running tests after the first failure:

- -
-jpm test --stop-on-error
-
--tbplPrint test output in Treeherder format
--times NUMBER -

Run tests NUMBER of times:

- -
-jpm test --times 2
-
-v --verboseVerbose operation.
--no-copy -
Use with caution because jpm run|test changes many preferences, never use with your main profile.
- -
This only applies when --profile is used.
- Disables the copying of the profile used, which allows one to reuse a profile.
- -

jpm xpi

- -

Эта команда собирает дополнение в пакет XPI. Это формат дополнений, которые можно легко установить Mozilla.

- -
jpm xpi
- -

It looks for a file called package.json in the current directory and creates the corresponding XPI file. It ignores any ZIPs or XPIs in the add-on's root, and any test files.

- -

Once you have built an XPI file you can distribute your add-on by submitting it to addons.mozilla.org.

- -

jpm xpi accepts the following option:

- - - - - - - - -
-v --verbose -

Verbose operation:

- -
-jpm xpi -v
-
- -

jpm post

- -

This command packages the add-on as an XPI file, the posts it to some url.

- -
jpm post
- -

It looks for a file called package.json in the current directory and creates a XPI file with which to post to the --post-url.

- -

jpm post accepts the following options:

- - - - - - - - - - - - -
--post-url URL -

The url to post the extension to after creating a XPI.

- -
-jpm post --post-url http://localhost:8888/
- -

See Using Post and Watchpost for more information.

-
-v --verbose -

Verbose operation:

- -
-jpm post --post-url http://localhost:8888/ -v
-
- -

jpm watchpost

- -

This command packages the add-on as an XPI file, the posts it to some url whenever a file in the current working directory changes.

- -
jpm watchpost
- -

Creates a XPI whenever a file in the current working directory changes and posts that to the --post-url.

- -

jpm watchpost accepts the following options:

- - - - - - - - - - - - -
--post-url URL -

The url to post the extension to after creating a XPI.

- -
-jpm watchpost --post-url http://localhost:8888/
- -

See Using Post and Watchpost for more information.

-
-v --verbose -

Verbose operation:

- -
-jpm watchpost --post-url http://localhost:8888/ -v
-
- -

Techniques

- -

Selecting a browser version

- -

By default, jpm run and jpm test will run the release version of Firefox. You can instruct jpm to use a different version in one of two ways:

- - - -

Using .jpmignore to ignore files

- -

Using .jpmignore is similar to using .gitignore with git, .hgignore with Mercurial, or .npmignore with npm. By using this file you can let jpm know which files you would like it to ignore when building a .xpi file with jpm xpi.

- -

Here is an example:

- -
# Ignore .DS_Store files created by mac
-.DS_Store
-
-# Ignore any zip or xpi files
-*.zip
-*.xpi
-
- -

A .jpmignore file with the above contents would ignore all zip files and .DS_Store files from the xpi generated by jpm xpi.

- -

Using profiles

- -

By default, jpm run uses a new profile each time it is executed. This means that any profile-specific data entered from one run of jpm will not, by default, be available in the next run.

- -

This includes, for example, any extra add-ons you installed, or your history, or any data stored using the simple-storage API.

- -

To make jpm use a specific profile, pass the --profile option, specifying the name of the profile you wish to use, or the path to the profile.

- -
jpm run --profile boogaloo
-
- -
jpm run --profile path/to/boogaloo
- -

If you supply --profile but its argument is not the name of or path to an existing profile, jpm will open the profile manager,  enabling you to select and existing profile or create a new one:

- -
jpm run --profile i-dont-exist
- -

Developing without browser restarts

- -

Because jpm run restarts the browser each time you invoke it, it can be a little cumbersome if you are making very frequent changes to an add-on. An alternative development model is to use the Extension Auto-Installer add-on: this listens for new XPI files on a specified port and installs them automatically. That way you can test new changes without needing to restart the browser:

- - - -

You could even automate this workflow with a simple script. For example:

- -
jpm watchpost --post-url http://localhost:8888/
-
- -

Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using jpm run. This means that if you want to see output from console.log() messages, you'll have to tweak a setting. See the documentation on logging levels for the details on this.

- -

Overloading the built-in modules

- -

The SDK modules you use to implement your add-on are built into Firefox. When you run or package an add-on using jpm run or jpm xpi, the add-on will use the versions of the modules in the version of Firefox that hosts it.

- -

As an add-on developer, this is usually what you want. But if you're developing the SDK modules themselves, of course, it isn't. In this case you need to:

- - - -
jpm run -o
-
- -

This instructs jpm to use the local copies of the SDK modules, not the ones in Firefox. If you don't want to set the JETPACK_ROOT environment variable, you can pass the location of your copy of the SDK modules along with -o:

- -
jpm run -o "/path/to/SDK/"
diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html deleted file mode 100644 index d9453e9767..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Создание простого Add-on (jpm) -slug: Mozilla/Add-ons/SDK/Tutorials/Getting_Started_(jpm) -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Getting_Started_(jpm) ---- -
-

The Add-on SDK includes a command-line tool that you use to initialize, run, test, and package add-ons. The current tool is called jpm, and is based on Node.js. It replaces the old cfx tool.

- -

You can use jpm from Firefox 38 onwards.

- -

This article describes how to develop using jpm.

-
- -

This tutorial walks through creating a simple add-on using the SDK.

- -

Prerequisites

- -

To create add-ons for Firefox using the SDK, you'll need:

- - - -

Initializing an empty add-on

- -

In the command prompt, create a new directory. Navigate to it, type jpm init, and hit enter:

- -
mkdir my-addon
-cd my-addon
-jpm init
-
- -

You'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file. For now, just press Enter to accept the default for each property. For more information on jpm init, see the jpm command reference.

- -

Once you've supplied a value or accepted the default for these properties, you'll be shown the complete contents of "package.json" and asked to accept it.

- -

Implementing the add-on

- -

Now you can write the add-on's code. Unless you've changed the value of "entry point" ("main" in package.json), this goes in "index.js" file in the root of your add-on. This file was created for you in the previous step. Open it and add the following code:

- -
var buttons = require('sdk/ui/button/action');
-var tabs = require("sdk/tabs");
-
-var button = buttons.ActionButton({
-  id: "mozilla-link",
-  label: "Visit Mozilla",
-  icon: {
-    "16": "./icon-16.png",
-    "32": "./icon-32.png",
-    "64": "./icon-64.png"
-  },
-  onClick: handleClick
-});
-
-function handleClick(state) {
-  tabs.open("http://www.mozilla.org/");
-}
-
- -
-

Note that "entry point" defaults to "index.js" in jpm, meaning that your main file is "index.js", and it is found directly in your add-on's root.

- -

In cfx, the entry point defaults to "main.js", and is located in the "lib" directory under the add-on's root.

-
- -

Save the file.

- -

Next, create a directory called "data" in your add-on's root, and save these three icon files to the "data" directory:

- - - - - - - - - - - - - - - - -
icon-16.png
icon-32.png
icon-64.png
- -

Back at the command prompt, type:

- -
jpm run
- -

This is the jpm command to run a new instance of Firefox with your add-on installed.

- -

If Firefox can not be located, you may need to provide the path to it (example in Ubuntu):

- - -
jpm run -b /usr/bin/firefox
- -

When Firefox launches, in the top-right corner of the browser you'll see an icon with the Firefox logo. Click the icon, and a new tab will open with http://www.mozilla.org/ loaded into it.

- -

That's all this add-on does. It uses two SDK modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. In this case, we've created a button whose icon is the Firefox icon, and added a click handler that loads the Mozilla home page in a new tab.

- -

Try editing this file. For example, we could change the page that gets loaded:

- -
var buttons = require('sdk/ui/button/action');
-var tabs = require("sdk/tabs");
-
-var button = buttons.ActionButton({
-  id: "mozilla-link",
-  label: "Visit Mozilla",
-  icon: {
-    "16": "./icon-16.png",
-    "32": "./icon-32.png",
-    "64": "./icon-64.png"
-  },
-  onClick: handleClick
-});
-
-function handleClick(state) {
-  tabs.open("https://developer.mozilla.org/");
-}
- -

At the command prompt, execute jpm run again. This time clicking it takes you to https://developer.mozilla.org/.

- -

Packaging the add-on

- -

When you've finished the add-on and are ready to distribute it, you'll need to package it as an XPI file. This is the installable file format for Firefox add-ons. You can distribute XPI files yourself or publish them to https://addons.mozilla.org so other users can download and install them.

- -

To build an XPI, just execute the command jpm xpi from the add-on's directory:

- -
jpm xpi
-
- -

You should see a message like:

- -
JPM info Successfully created xpi at /path/to/getting-started/@getting-started.xpi
-
- -

To test that this worked, try installing the XPI file in your own Firefox installation. You can do this by pressing the Ctrl+O key combination (Cmd+O on Mac) from within Firefox, or selecting the "Open" item from Firefox's "File" menu. This will bring up a file selection dialog: navigate to the "@getting-started.xpi" file, open it and follow the prompts to install the add-on.

- -

Summary

- -

In this tutorial we've built and packaged an add-on using three commands:

- - - -

These are the three main commands you'll use when developing SDK add-ons. There's comprehensive reference documentation covering all the commands you can use and all the options they take.

- -

The add-on code itself uses two SDK modules, action button and tabs. There's reference documentation for all the high-level and low-level APIs in the SDK.

- -

What's next?

- -

To get a feel for some of the things you can do with the SDK APIs, try working through some of the tutorials.

diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/index.html deleted file mode 100644 index 277c5573d9..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Tutorials -slug: Mozilla/Add-ons/SDK/Tutorials -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials ---- -

Эта страница содержит практические статьи о том как выполнять конкретные задачи используя SDK.

- -
-

Начало работы

- -
-
-
-
Установка
-
Скачивание, установка и инициализация комплекта средств разработки (SDK) для Windows, OS X и Linux.
-
- -
-
Исправление проблем
-
Несколько указаний для фиксации общих пролбем и получение дополнительной помощи.
-
-
- -
-
-
Создание простого дополнения (Add-on)
-
Пошаговое руководство по созданию простого дополнения при помощи SDK и jpm.
-
-
-
- -
-

Создание пользовательского интерфейса

- -
-
-
-
Добавление кнопи панели инструментов
-
Прикрепление кнопки к панели инструментов дополнений Firefox.
-
Добавление элементов меню Firefox
-
Добавление элементов в основные меню Firefox.
-
-
- -
-
-
Отображение высплывающего окна (popup)
-
Отображение всплывающего диалогового окна и его реализация с помощью HTML и JavaScript.
-
Добавление элемента контекстного меню
-
Добавление элементов контекстных меню Firefox.
-
-
-
- -
-

Взаимодействие с браузером

- -
-
-
-
Загрузка вебстраниц
-
Загрузка вебстраниц в новой вкладке или новом окне с использованием модуля вкладок (tabs module), и доступ к их содержимому.
-
Отслеживание загрузки страниц
-
Использование модуля вкладок (tabs module) для получения оповещений о загрузке новых вебстраниц и доступа к их содержимому.
-
-
- -
-
-
Получение списка открытых вкладок
-
Использование модуля вкладок (tabs module) для перебора открытых вкладок и доступа к их содержимому.
-
-
-
- -
-

Изменение вебстраниц

- -
-
-
-
Изменение вебстраниц на основе URL
-
Создание фильтров для вебстраниц на основе их URL: всякий раз, когда загрузится вебстраница, чей URL соответствует фильтру, на ней выполнится заданный сценарий.
-
-
- -
-
-
Изменение активной вебстраницы
-
Динамическая загрузка сценария на текущую активную вебстраницу.
-
-
-
- -
-

Техники разработки

- -
-
-
-
Логгирование
-
Вывод сообщений в консоль для диагностики.
-
Создание повторно используемых модулей
-
Структурирование дополнения в отдельные модули, чтобы упростить разработку, отладку и поддержку. Создание повторно используемых пакетов, содержащих ваши модули, чтобы другие разработчики могли их использовать.
-
Модульное тестирование
-
Написание и запуск модульных тестов с использованием тестовой среды SDK.
-
Полномочия Chrome
-
Получение доступа к объекту Components, позволит вашему дополнению загружать и использовать любой объект XPCOM.
-
Создание целей события
-
Включение объектов вашего определения для выпуска собственных событий.
-
-
- -
-
-
Отслеживание загрузки и выгрузки
-
Получение уведомлений, когда Firefox загрузил или выгрузил ваше дополнение и передача аргументов вашему дополнению из командной строки.
-
Использование сторонних модулей
-
Установка и использование дополнительных модулей не входящих в SDK.
-
Локализация
-
Написание локализуемого кода.
-
Мобильная разработка
-
Разработка дополнений для Firefox Mobile на Android.
-
Отладчик дополнения
-
Отладка JavaScript вашего дополнения.
-
-
-
- -
-

Объединение

- -
-
-
-
Аннотация дополнения
-
Пошаговое руководство относительно сложного дополнения.
-
-
-
- -

 

diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html deleted file mode 100644 index 48b8923923..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Installation -slug: Mozilla/Add-ons/SDK/Tutorials/Installation -translation_of: Mozilla/Add-ons/SDK/Tools/jpm#Installation ---- -

Prerequisites

-

To develop with the Add-on SDK, you'll need:

- -

Alternatively, if you use Firefox Nightly, you can get the latest development version from its GitHub repository.

-

Installation on Mac OS X / Linux

-

Extract the file contents wherever you choose, and navigate to the root directory of the SDK with a shell/command prompt. For example:

-
tar -xf addon-sdk.tar.gz
-cd addon-sdk
-
-

Then run if you're a Bash user (most people are):

-
source bin/activate
-
-

And if you're a non-Bash user, you should run:

-
bash bin/activate
-
-

Your command prompt should now have a new prefix containing the name of the SDK's root directory:

-
(addon-sdk)~/mozilla/addon-sdk >
-
-

Installation on Mac using Homebrew

-

If you're a Mac user, you can instead choose to use Homebrew to install the SDK, using the following command:

-
brew install mozilla-addon-sdk
-

Once this has completed successfully, you can use the cfx program at your command line at any time: you don't need to run bin/activate.

-

Installation on Windows

-

Extract the file contents wherever you choose, and navigate to the root directory of the SDK with a shell/command prompt. For example:

-
7z.exe x addon-sdk.zip
-cd addon-sdk
-
-

Then run:

-
bin\activate
-
-

Your command prompt should now have a new prefix containing the full path to the SDK's root directory:

-
(C:\Users\mozilla\sdk\addon-sdk) C:\Users\Work\sdk\addon-sdk>
-
-

activate

-

The activate command sets some environment variables that are needed for the SDK. It sets the variables for the current command prompt only. If you open a new command prompt, the SDK will not be active in the new prompt. until you type activate again.

-

This means that you can have multiple copies of the SDK in different locations on disk and switch between them, or even have them both activated in different command prompts at the same time.

-

Making activate permanent

-

By setting these variables permanently in your environment so every new command prompt reads them, you can make activation permanent. Then you don't need to type activate every time you open up a new command prompt.

-

Because the exact set of variables may change with new releases of the SDK, it's best to refer to the activation scripts to determine which variables need to be set. Activation uses different scripts and sets different variables for bash environments (Linux and Mac OS X) and for Windows environments.

-

Windows

-

On Windows, bin\activate uses activate.bat, and you can make activation permanent using the command line setx tool or the Control Panel.

-

Linux/Mac OS X

-

On Linux and Mac OS X, source bin/activate uses the activate bash script, and you can make activation permanent using your ~/.bashrc (on Linux) or ~/.bashprofile (on Mac OS X).

-

As an alternative to this, you can create a symbolic link to the cfx program in your ~/bin directory:

-
ln -s PATH_TO_SDK/bin/cfx ~/bin/cfx
-
-

If you used Homebrew to install the SDK, the environment variables are already set permanently for you.

-

Sanity check

-

Run this at your shell prompt:

-
cfx
-
-

It should produce output whose first line looks something like this, followed by many lines of usage information:

-
Usage: cfx [options] [command]
-
-

This is the cfx command-line program. It's your primary interface to the Add-on SDK. You use it to launch Firefox and test your add-on, package your add-on for distribution, view documentation, and run unit tests.

-

Problems?

-

Try the Troubleshooting page.

-

Next Steps

-

Next, take a look at the Getting Started With cfx tutorial, which explains how to create add-ons using the cfx tool.

diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/creating_annotations/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/creating_annotations/index.html" deleted file mode 100644 index 07cecddaf5..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/creating_annotations/index.html" +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Добавление заметок -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Creating_annotations -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Creating_annotations ---- -

Мы будем использовать два объекта для создания заметок: модификатор страницы - чтобы найти элементы, для которых пользователь может оставить заметку и панель для ввода текста заметки.

-

Селектор модификации страницы

-

Селектор контент-скриптов

-

Контент-скрипт для селекторамодификации страницы будет ипользовать jQuery для поиска элементов и манипуляций над ними.

-

Эго главная задача - обработка "подходящего элемента": это элемент страницы, который подходит для добавления заметки на него. Подходящий элемент будет подсвечен и будет иметь обработчик событий, который будет отправлять сообщения основному коду расширения.

-

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

-
var matchedElement = null;
-var originalBgColor = null;
-var active = false;
-
-function resetMatchedElement() {
-  if (matchedElement) {
-    (matchedElement).css('background-color', originalBgColor);
-    (matchedElement).unbind('click.annotator');
-  }
-}
-
-self.on('message', function onMessage(activation) {
-  active = activation;
-  if (!active) {
-    resetMatchedElement();
-  }
-});
-

Данный селектор ожидает вхождения события jQuery mouseenter.

-

 When a mouseenter event is triggered the selector checks whether the element is eligible for annotation. An element is eligible if it, or one of its ancestors in the DOM tree, has an attribute named "id". The idea here is to make it more likely that the annotator will be able to identify annotated elements correctly later on.

-

If the page element is eligible for annotation, then the selector highlights that element and binds a click handler to it. The click handler sends a message called show back to the main add-on code. The show message contains: the URL for the page, the ID attribute value, and the text content of the page element.

-
$('*').mouseenter(function() {
-  if (!active || $(this).hasClass('annotated')) {
-    return;
-  }
-  resetMatchedElement();
-  ancestor = $(this).closest("[id]");
-  matchedElement = $(this).first();
-  originalBgColor = $(matchedElement).css('background-color');
-  $(matchedElement).css('background-color', 'yellow');
-  $(matchedElement).bind('click.annotator', function(event) {
-    event.stopPropagation();
-    event.preventDefault();
-    self.port.emit('show',
-      [
-        document.location.toString(),
-        $(ancestor).attr("id"),
-        $(matchedElement).text()
-      ]
-   );
-  });
-});
-

Conversely, the add-on resets the matched element on mouseout:

-
$('*').mouseout(function() {
-  resetMatchedElement();
-});
-

Save this code in a new file called selector.js in your add-on's data directory.

-

Because this code uses jQuery, you'll need to download that as well, and save it in data.

-

Updating main.js

-

Go back to main.js and add the code to create the selector into the main function:

-
var selector = pageMod.PageMod({
-  include: ['*'],
-  contentScriptWhen: 'ready',
-  contentScriptFile: [data.url('jquery-1.4.2.min.js'),
-                      data.url('selector.js')],
-  onAttach: function(worker) {
-    worker.postMessage(annotatorIsOn);
-    selectors.push(worker);
-    worker.port.on('show', function(data) {
-      console.log(data);
-    });
-    worker.on('detach', function () {
-      detachWorker(this, selectors);
-    });
-  }
-});
-

Make sure the name you use to load jQuery matches the name of the jQuery version you downloaded.

-

The page-mod matches all pages, so each time the user loads a page the page-mod emits the attach event, which will call the listener function we've assigned to onAttach. The handler is passed a worker object. Each worker represents a channel of communication between the add-on code and any content scripts running in that particular page context. For a more detailed discussion of the way page-mod uses workers, see the page-mod documentation.

-

In the attach handler we do three things:

- -

At the top of the file import the page-mod module and declare an array for the workers:

-
var pageMod = require('sdk/page-mod');
-var selectors = [];
-

Add detachWorker:

-
function detachWorker(worker, workerArray) {
-  var index = workerArray.indexOf(worker);
-  if(index != -1) {
-    workerArray.splice(index, 1);
-  }
-}
-

Edit toggleActivation to notify the workers of a change in activation state:

-
function activateSelectors() {
-  selectors.forEach(
-    function (selector) {
-      selector.postMessage(annotatorIsOn);
-  });
-}
-
-function toggleActivation() {
-  annotatorIsOn = !annotatorIsOn;
-  activateSelectors();
-  return annotatorIsOn;
-}
-

We'll be using this URL in all our screenshots. Because cfx run doesn't preserve browsing history, if you want to play along it's worth taking a note of the URL.

-

Save the file and execute cfx run again. Activate the annotator by clicking the widget and load a page: the screenshot below uses http://blog.mozilla.com/addons/2011/02/04/ overview-amo-review-process/. You should see the highlight appearing when you move the mouse over certain elements:

-

Click on the highlight and you should see something like this in the console output:

-
  info: show
-  info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/,
-  post-2249,When you submit a new add-on, you will have to choose between 2
-  review tracks: Full Review and Preliminary Review.
-
-

Annotation Editor Panel

-

So far we have a page-mod that can highlight elements and send information about them to the main add-on code. Next we will create the editor panel, which enables the user to enter an annotation associated with the selected element.

-

We will supply the panel's content as an HTML file, and will also supply a content script to execute in the panel's context.

-

So create a subdirectory under data called editor. This will contain two files: the HTML content, and the content script.

-

Annotation Editor HTML

-

The HTML is very simple:

-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
-<head>
-  <title>Annotation</title>
-  <style type="text/css" media="all">
-  body {
-    font: 100% arial, helvetica, sans-serif;
-    background-color: #F5F5F5;
-  }
-  textarea {
-    width: 180px;
-    height: 180px;
-    margin: 10px;
-    padding: 0px;
-  }
-  </style>
-
-</head>
-
-<body>
-
-<textarea rows='10' cols='20' id='annotation-box'>
-</textarea>
-
-</body>
-
-</html>
-

Save this inside data/editor as annotation-editor.html.

-

Annotation Editor Content Script

-

In the corresponding content script we do two things:

- -

Here's the code:

-
var textArea = document.getElementById('annotation-box');
-
-textArea.onkeyup = function(event) {
-  if (event.keyCode == 13) {
-    self.postMessage(textArea.value);
-    textArea.value = '';
-  }
-};
-
-self.on('message', function() {
-  var textArea = document.getElementById('annotation-box');
-  textArea.value = '';
-  textArea.focus();
-});
-

Save this inside data/editor as annotation-editor.js.

-

Updating main.js Again

-

Now we'll update main.js again to create the editor and use it.

-

First, import the panel module:

-
var panels = require('sdk/panel');
-

Then add the following code to the main function:

-
var annotationEditor = panels.Panel({
-  width: 220,
-  height: 220,
-  contentURL: data.url('editor/annotation-editor.html'),
-  contentScriptFile: data.url('editor/annotation-editor.js'),
-  onMessage: function(annotationText) {
-    if (annotationText) {
-      console.log(this.annotationAnchor);
-      console.log(annotationText);
-    }
-    annotationEditor.hide();
-  },
-  onShow: function() {
-    this.postMessage('focus');
-  }
-});
-

We create the editor panel but don't show it. We will send the editor panel the focus message when it is shown, so it will give the text area focus. When the editor panel sends us its message we log the message and hide the panel.

-

The only thing left is to link the editor to the selector. So edit the message handler assigned to the selector so that on receiving the show message we assign the content of the message to the panel using a new property "annotationAnchor", and show the panel:

-
var selector = pageMod.PageMod({
-  include: ['*'],
-  contentScriptWhen: 'ready',
-  contentScriptFile: [data.url('jquery-1.4.2.min.js'),
-                      data.url('selector.js')],
-  onAttach: function(worker) {
-    worker.postMessage(annotatorIsOn);
-    selectors.push(worker);
-    worker.port.on('show', function(data) {
-      annotationEditor.annotationAnchor = data;
-      annotationEditor.show();
-    });
-    worker.on('detach', function () {
-      detachWorker(this, selectors);
-    });
-  }
-});
-

Execute cfx run again, activate the annotator, move your mouse over an element and click the element when it is highlighted. You should see a panel with a text area for a note:

-

Enter the note and press the return key: you should see console output like this:

-
  info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/,
-  post-2249,When you submit a new add-on, you will have to choose between 2
-  review tracks: Full Review and Preliminary Review.
-  info: We should ask for Full Review if possible.
-
-

That's a complete annotation, and in the next section we'll deal with storing it.

diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/implementing_the_widget/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/implementing_the_widget/index.html" deleted file mode 100644 index ef43991658..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/implementing_the_widget/index.html" +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Реализация Виджета -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Implementing_the_widget -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Implementing_the_widget ---- -

Мы хотим, чтобы виджет выполнял две вещи:

- -

Так как событие click не различает левую и правую кнопки мыши, мы будем использовать контент-скрипт для захвата событий клика мышью и отправлять соответствующее сообщение назад, нашему расширению.

-

Виджет должен иметь две иконки: одна для активного состояния, вторая для неактивного.

-

В итоге нам понадобится создать три файла: контент-скрипт для Виджета и две иконки.

-

Внутри папки data создайте папку с именем widget. В этой папке мы будем хранить файлы Виджета. (Вам не обязательно создавать отдельную папку, можете просто хранить файлы Виджета в папке data. Но в нашем случае, расширение будет хорошо структурировано.)

-

Контент-скрипт Виджета

-

Контент-скрипт Виджета просто следит за нажатиями левой и правой кнопок мыши и отправляет соответствующее сообщение коду расширения:

-
this.addEventListener('click', function(event) {
-  if(event.button == 0 && event.shiftKey == false)
-    self.port.emit('left-click');
-
-  if(event.button == 2 || (event.button == 0 && event.shiftKey == true))
-    self.port.emit('right-click');
-    event.preventDefault();
-}, true);
-

Сохраните этот файл в папку data/widget под названием widget.js.

-

Иконки Виджета

-

Вы можете скопировать эти иконки:

-

-

(Вы также можете создать свои собственные иконки, если чуствуете, что вас поситила муза.) Сохраните их в папку data/widget.

-

main.js

-

Теперь, в папке lib откройте main.js и добавьте следующий код:

-
var widgets = require('sdk/widget');
-var data = require('sdk/self').data;
-
-var annotatorIsOn = false;
-
-function toggleActivation() {
-  annotatorIsOn = !annotatorIsOn;
-  return annotatorIsOn;
-}
-
-exports.main = function() {
-
-  var widget = widgets.Widget({
-    id: 'toggle-switch',
-    label: 'Annotator',
-    contentURL: data.url('widget/pencil-off.png'),
-    contentScriptWhen: 'ready',
-    contentScriptFile: data.url('widget/widget.js')
-  });
-
-  widget.port.on('left-click', function() {
-    console.log('activate/deactivate');
-    widget.contentURL = toggleActivation() ?
-              data.url('widget/pencil-on.png') :
-              data.url('widget/pencil-off.png');
-  });
-
-  widget.port.on('right-click', function() {
-      console.log('show annotation list');
-  });
-}
-

Аннотатор по-умолчанию отключен. Этот скрипт создает Виджет и реагирует на сообщения контент-скрипта, путем переключения состояния Виджета. Внимание: согласно багу bug 626326, контекстное меню панели дополнений будет отображаться вне зависимости от вызова event.preventDefault() в контент-скрипте Виджета. Так как мы пока не имеем кода для отображения заметок, мы просто выведем в консоль событие нажатия правой кнопки.

-

Теперь, перейдя в папку annotator выполните команду cfx run. Вы должны увидеть Виджет в панели дополнений:

-

-

Левый и правый клики должы выводить соответсвующие сообщения в консоль, и левый клик также должен менять иконку для отображения состояния активности Виджета.

-

 

-

Далее мы добавим реализацию функции создания аннотаций.

diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/index.html" deleted file mode 100644 index eab37823c0..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/index.html" +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Комментатор -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator ---- -

{{AddonSidebar}}

- -
-

Запрещено в Firefox 29 и удалено в Firefox 38.

- -

Предупреждение: это руководство пологается на впоследствии удалённый Widget API и больше не работает с Firefox.

- -

The widget API is deprecated from Firefox 29 onwards. Please see the ui module for replacements. In particular, for a simple button, try the action button or toggle button APIs, and for a more complex widget try the toolbar or sidebar APIs.

-
- -

В этом уроке мы создадим расширение, которое использует множество различных компонентов высокоуровнего API.

- -

Это расширение (Аннотатор) позволит пользователю выделять элементы веб-страниц и добавлять к ним заметки (аннотации). Аннотатор будет сохранять заметки, добавленные пользователем. Когда пользователь посещает веб-страницу, содержащую элементы с прикрепленными к ним заметками - эти элементы подсвечиваются. Если пользователь наведет курсор на такой элемент страницы, то будет отображена заметка, ассоциированная с этим элементом.

- -

Далее мы кратко рассмотрим архитектуру Аннотатора и поэтапно пройдемся по реализации разных частей расширения.

- -

Завершенное расширение вы можете найти в папке examples из SDK.

- - diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/overview/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/overview/index.html" deleted file mode 100644 index 08e4713b33..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\260\320\275\320\275\320\276\321\202\320\260\321\202\320\276\321\200/overview/index.html" +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Краткий обзор -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Overview -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Overview ---- -

Аннотатор использует контент-скрипты для реализации пользовательских интерфейсов, получения ввода, и для работы со страницами, посещаемыми пользователем.

-

Модуль main содержит логику приложения и производит операции между различными объектами SDK.

-

Операции между модулем main и различными контент-скриптами можно изобразить следующим образом:

-

-

Пользовательский интерфейс

-

Основной пользовательский интерфейс состоит из Виджета и трех панелей:

- -

В дополнении, мы будем использовать модуль Оповещений (notifications), чтобы сообщать пользователю, когда в хранилище закончилось свободное место.

-

Работаем с DOM

-

Мы будем использовать два объекта page-mods для произведения операций над DOM веб-страниц, которые посещает пользователь:

- -

Обработка данных

-

Мы будем использовать модуль simple-storage для хранения заметок.

-

Поскольку мы сохраняем потенциально секретную информацию, мы хотим оградить пользователя от создания заметок в приватном режиме браузера. Простейший способ решения этой проблемы, это удаление ключа "private-browsing" из файла "package.json" расширения. Если мы удалим этот ключ, то расширение не получит доступ к окнам в режиме приватного просмотра и Виджет Аннотатора не будет отображаться в приватных окнах.

-

Приступаем к работе

-

Давайте начнем с создания папки, с именем "annotator". Перейдите в эту папку и введите cfx init.

-

Далее мы разработаем Виджет.

diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\264\320\276\320\261\320\260\320\262\320\273\320\265\320\275\320\270\320\265_\320\272\320\275\320\276\320\277\320\272\320\270_\320\275\320\260_\320\277\320\260\320\275\320\265\320\273\321\214_\320\270\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\320\276\320\262/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\264\320\276\320\261\320\260\320\262\320\273\320\265\320\275\320\270\320\265_\320\272\320\275\320\276\320\277\320\272\320\270_\320\275\320\260_\320\277\320\260\320\275\320\265\320\273\321\214_\320\270\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\320\276\320\262/index.html" deleted file mode 100644 index 7b6e8bf507..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\264\320\276\320\261\320\260\320\262\320\273\320\265\320\275\320\270\320\265_\320\272\320\275\320\276\320\277\320\272\320\270_\320\275\320\260_\320\277\320\260\320\275\320\265\320\273\321\214_\320\270\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\320\276\320\262/index.html" +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Добавление кнопки на панель инструментов -slug: Mozilla/Add-ons/SDK/Tutorials/Добавление_кнопки_на_панель_инструментов -tags: - - Add-on SDK - - Дополнение -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Adding_a_Button_to_the_Toolbar ---- -
-

Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.

-
- -

{{LegacyAddonsNotice}}{{AddonSidebar}}

- -
-

Для понимания этого руководства необходимо изучить статью basics of jpm (основы jpm).

-
- -

Для добавления кнопки на панель инструментов (toolbar, тулбар) используются модули action button или toggle button.

- -

Создайте новую папку, перейдите в неё и запустите jpm init, приняв всё по умолчанию.

- -

Создайте папку "data"

- -
mkdir data
- -

и сохраните три файла иконок в этой папке:

- - - - - - - - - - - - - - - - -
icon-16.png
icon-32.png
icon-64.png
- -

После, откройте файл "index.js", расположенный в корне каталога дополнения, и допишите этот код:

- -
var buttons = require('sdk/ui/button/action');
-var tabs = require("sdk/tabs");
-
-var button = buttons.ActionButton({
-  id: "mozilla-link",
-  label: "Visit Mozilla",
-  icon: {
-    "16": "./icon-16.png",
-    "32": "./icon-32.png",
-    "64": "./icon-64.png"
-  },
-  onClick: handleClick
-});
-
-function handleClick(state) {
-  tabs.open("https://www.mozilla.org/");
-}
- -

Запустите дополнение через jpm run. Кнопка будет добавлена на тулбар (ищите сверху в окне браузера):

- -

Вы не сможете установить место первоначального появления кнопки, но пользователь сможет её переместить, используя настройки браузера. Атрибут id является обязательным. Он используется, в частности, для запоминания позиции кнопки на панели, поэтому в следующих версиях своего дополнения вы его не сможете изменить.

- -

Нажатие кнопки откроет в новой вкладке сайт https://www.mozilla.org/ .

- -

Задание иконки

- -

Свойство icon может содержать одну иконку или набор (различных размеров, как в примере выше). Если указать набор иконок разных размеров, то браузер будет автоматически выбирать размер в зависимости от разрешения экрана и расположения на экране. Более подробная информация о иконках.

- -

Файл с иконкой должен быть внутри дополнения. Недопустимы ссылки на внешние фалы.

- -

Вы можете изменить иконку в любое время через установку свойства icon кнопки. Также можно изменить иконку и другие свойства состояния глобально для окна брайзера или только для вкладки. Узнать об этом можно в статье.

- -

Привязка панели

- -

Если необходимо привязать к кнопке панель, то используйте toggle button API. Этот API такой же как action button API, кроме того, что добавлено булево свтйство checked, которое переключается, когда нажимается конпка.  Для связи в панелью нужнопередать кнопку в функцию show() панели. Для уточнения деталей, изучите документацию toggle button's documentation.

- -

Вывод сложного контента

- -

Для созлания более сложного пользовательского интерфейса, чем доступен через кнопку, используйте toolbar API. С этим API вы получите доступ к полным гризонтальным полосам тулбара. Можно добавлять кнопки на панель, и фреймы (frames), которые могут содержать HTML, CSS и JavaScript.

- -

Материал для изучения

- - diff --git "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\277\321\200\320\276\321\202\320\276\320\272\320\276\320\273\320\270\321\200\320\276\320\262\320\260\320\275\320\270\320\265/index.html" "b/files/ru/mozilla/add-ons/sdk/tutorials/\320\277\321\200\320\276\321\202\320\276\320\272\320\276\320\273\320\270\321\200\320\276\320\262\320\260\320\275\320\270\320\265/index.html" deleted file mode 100644 index d0ab8d6f79..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/tutorials/\320\277\321\200\320\276\321\202\320\276\320\272\320\276\320\273\320\270\321\200\320\276\320\262\320\260\320\275\320\270\320\265/index.html" +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Протоколирование (Логирование) -slug: Mozilla/Add-ons/SDK/Tutorials/Протоколирование -tags: - - Логирование - - Протоколирование -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Logging ---- -
-

Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.

-
- -

{{LegacyAddonsNotice}}{{AddonSidebar}}

- -
Перед использованием, вам нужно изучить основы jpm.
- -

Консоль для DOM-объекта полезна для отладки JavaScript. Так как DOM-объекты недоступны для главного кода дополнения (add-on), то SDK предоставляет свой собственный глобальный объект "консоль" (console) с большинством таких же методов, как и у DOM-консоли, включая методы для протоколирвоания ошибок (error), предупреждений (warning) или информационных сообщений. Для доступа к консоли не нужно получать что-либо, используя require(). Она уже доступна автоматически.

- -

Метод console.log() выводит информационное сообщение:

- -
console.log("Hello World");
-
- -

Попробуйте:

- - - -

Firefox запустится, и в терминале, где вы ввели jpm run, появится следующая строка:

- -
info: Hello World!
-
- -

Консоль в скриптах Content Scripts

- -

Вы можете использовать консоль в скриптах content scripts так же, как и вашем главном коде дополнения. Следующий аддон (add-on) выведет в лог HTML-содержимое каждой закладки, загруженной пользователем, используя console.log() изнутри скрипта content script:

- -
require("sdk/tabs").on("ready", function(tab) {
-  tab.attach({
-    contentScript: "console.log(document.body.innerHTML);"
-  });
-});
-
- -

Консоль Output

- -

Если вы запускаете дополнение из терминала (например, выполня jpm run или jpm test), тогда сообщения консоли появятся в этом же терминале.

- -

Если вы установили расширение в Firefox тогде сообщения появятся в консоли браузера Firefox.

- -

Но обратите внимание, что по умолчанию вызовы console.log() не отобразят ничего в Error Console для любых установленных дополнений. Это правило работает и для дополнений, установленных с использованием Add-on Builder, и для установленных с помощью утилит, таких как Extension Auto-installer.

- -

Смотрите "Уровни логирования" в справочной документации для более подробной информации.

- -

Дальнейшее изучение

- -

Полное API консоли смотри в API-справочнике.

diff --git "a/files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" "b/files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" deleted file mode 100644 index 987a420410..0000000000 --- "a/files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Builder -slug: Mozilla/Add-ons/SDK/проба -translation_of: Archive/Add-ons/Add-on_SDK/Builder ---- -

The Add-on Builder was a web-based development environment that allowed developers to create add-ons using the SDK APIs, but without needing to use the cfx command line tool. It was retired on April 1, 2014, and the "builder.addons.mozilla.org" domain now redirects to this page.
-
- If you have only used the SDK through the Builder, you already know most of what you need to know to develop using just the SDK. The high-level and low-level APIs used for Builder add-ons are exactly the same for Builder and SDK. To switch to the SDK:

- - diff --git "a/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" "b/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" deleted file mode 100644 index 934e40e904..0000000000 --- "a/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" +++ /dev/null @@ -1,353 +0,0 @@ ---- -title: Загружаемые расширения -slug: Mozilla/Add-ons/загрузочные_расширения -tags: - - Bootstrapped - - Extensions - - add-on - - Дополнения -translation_of: Archive/Add-ons/Bootstrapped_extensions ---- -
-

Support for extensions using XUL/XPCOM or the Add-on SDK was removed in Firefox 57, released November 2017. As there is no supported version of Firefox enabling these technologies, this page will be removed by December 2020.

-
- -

{{LegacyAddonsNotice}}{{AddonSidebar}}

- -

{{ gecko_minversion_header("2.0") }}

- -

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

- -

Движок Gecko 2.0 {{ geckoRelease("2.0") }} вводит загружаемые расширения (bootstrapped extensions). Это специальные расширения, которые вместо использования наложения на интерфейс, сами програмно добавляют себя в приложение. Это делается запуском специального скрипта из файла, который включен в расширение и содержит функции, вызываемые браузером, для того чтобы установить, удалить, загрузить, выгрузить.

- -

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

- -

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

- -

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:

- - - -

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

- - - -

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:

- - - -

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 {{ ifmethod("nsIComponentManager", "addBootstrappedManifestLocation") }} and {{ ifmethod("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 {{ domxref("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:

- -
<em:bootstrap>true</em:bootstrap>
- -

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.

- -

startup

- -

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(
-  data,
-  reason
-);
-
- -
Parameters
- -
-
data
-
A bootstrap data structure.
-
reason
-
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.
-
- -

shutdown

- -

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(
-  data,
-  reason
-);
-
- -
Parameters
- -
-
data
-
A bootstrap data structure.
-
reason
-
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.
-
- -

install

- -

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.

- -
void install(
-  data,
-  reason
-);
-
- -
Parameters
- -
-
data
-
A bootstrap data structure.
-
reason
-
One of the reason constants, indicating why the extension is being installed. This will be one of ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.
-
- -

uninstall

- -

This function is called after the last call to shutdown() before a particular version of an extension is uninstalled.

- -
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(
-  data,
-  reason
-);
-
- -
Parameters
- -
-
data
-
A bootstrap data structure.
-
reason
-
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:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConstantValueDescription
APP_STARTUP1The application is starting up.
APP_SHUTDOWN2The application is shutting down.
ADDON_ENABLE3The add-on is being enabled.
ADDON_DISABLE4The add-on is being disabled. (Also sent during uninstallation)
ADDON_INSTALL5The add-on is being installed.
ADDON_UNINSTALL6The add-on is being uninstalled.
ADDON_UPGRADE7The add-on is being upgraded.
ADDON_DOWNGRADE8The 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:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
idstringThe ID of the add-on being bootstrapped.
versionstringThe version of the add-on being bootstrapped.
installPathnsIFileThe 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.
resourceURInsIURIA 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. {{ gecko_minversion_inline("7.0") }}
oldVersionstringThe previously installed version, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is install or startup. {{ gecko_minversion_inline("22.0") }}
newVersionstringThe version to be installed, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is shutdown or uninstall. {{ gecko_minversion_inline("22.0") }}
- -
-

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. -
  3. File: chrome.manifest
  4. -
  5. File: bootstrap.js
  6. -
  7. Folder: locale -
      -
    1. Folder: VALID_LOCALE_HERE -
        -
      1. File: ANYTHING.properties
      2. -
      -
    2. -
    -
  8. -
- -

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. -
  3. The doctype must be defined point to a DTD file in your locale folder such as: <!DOCTYPE html SYSTEM "chrome://l10n/locale/mozilla.dtd">
  4. -
  5. Must add xmlns attribute to html tag for example: <html xmlns="http://www.w3.org/1999/xhtml">
  6. -
  7. If you have multiple DTD files read on here: Using multiple DTDs
  8. -
- -

The bare minimum needed is:

- -
    -
  1. File: install.rdf
  2. -
  3. File: chrome.manifest
  4. -
  5. File: bootstrap.js
  6. -
  7. Folder: locale -
      -
    1. Folder: VALID_LOCALE_HERE -
        -
      1. File: ANYTHING.dtd
      2. -
      -
    2. -
    -
  8. -
- -

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

- - diff --git "a/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" "b/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" deleted file mode 100644 index 4442856118..0000000000 --- "a/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Рекомендации по повышению производительности расширений -slug: Mozilla/Add-ons/Рекомендации_по_повышению_производительности_расширений -tags: - - Быстродействие - - Лучшие практики - - Плагины - - Производительность - - Расширения - - Руководство -translation_of: Archive/Add-ons/Performance_best_practices_in_extensions ---- -

Одно из самых значительных преимуществ браузера Firefox заключается в его чрезвычайной расширяемости. Благодаря дополнениям можно сделать практически что угодно. Есть и обратная сторона медали: плохо написанные расширения могут оказывать серьезное влияние на просмотр сайтов, в том числе и на производительность браузера Firefox в целом. Эта статья предлагает вашему вниманию лучшие практики и рекомендации, которые позволят повысить производительность и быстродействие не только вашего расширения, но также и самого браузера Firefox.

- -

Увеличиваем скорость запуска

- -

Расширения загружаются и выполняются всякий раз, когда открывается новое окно браузера. Это значит, что при каждом открытии окна ваше расширение может задерживать вывод желаемого контента на экран. Есть несколько способов уменьшения времени задержки вывода пользовательского контента.

- -

Загружайте только то, что вам действительно требуется

- -

В момент запуска плагина не следует загружать то, что понадобится только после нажатия пользователем на кнопку, или то, что понадобится только при включенной опции, если сейчас она выключена. Если ваше расширение предоставляет функции, доступные только после авторизации пользователя в сервисе, не следует загружать ресурсы для этих функций до тех пор, пока пользователь фактически не пройдет процедуру авторизации.

- -

Используйте модули JavaScript

- -

Вы можете создать собственный модуль JavaScript, объединив набор функций, которые нужны только в определенных ситуациях. Это упростит загрузку блоков кода вашего расширения на лету, вместо загрузки всего сразу.

- -

Несмотря на то, что модули JavaScript могут быть чрезвычайно полезны и давать прирост производительности, они должны применяться разумно. Загрузка модулей все же несет небольшие затраты, поэтому разбивка кода на ненужные уровни может привести к негативным результатам. Код должен быть разбит на модули так, чтобы от этого улучшалась его понятность, а загрузка крупных или требующих больших затрат блоков кода могла быть значительно отсрочена.

- -

Отсрочивайте все, что возможно

- -

У большинства расширений есть обработчик события загрузки в главном оверлее, который выполняет функцию при запуске браузера. Выполняйте в этой функции как можно меньше кода. Окно браузера зависает до тех пор, пока обработчик загрузки вашего плагина полностью не выполнится, поэтому чем больше в нем осуществляется действий, тем медленнее Firefox кажется пользователю.

- -

Если что-то можно сделать пусть даже на долю секунды позже, используйте методы {{ interface("nsITimer") }} или {{ domxref("window.setTimeout()") }} для того, чтобы отложить это действие на потом. Даже короткая отсрочка может иметь большое влияние на быстродействие.

- -

Общие вопросы производительности

- -

Избегайте утечек памяти

- -

Утечки памяти вынуждают сборщик мусора и сборщик циклических ссылок (cycle collector) выполнять больший объем работы, а это в значительной мере сказывается на быстродействии.

- -

Зомби-ячейки (zombie compartments) - это особый вид утечки памяти, который можно легко выявить. Загляните на страницу Зомби-ячейки, особенно раздел Проактивная проверка плагинов.

- -

Ознакомьтесь с разделом Распространенные причины утечек памяти в расширениях, чтобы узнать, как избежать возникновения зомби-ячеек и других видов утечек.

- -

Помимо поиска различных видов утечек памяти, стоит также проверить функционал вашего расширения и содержимое вкладки about:memory на предмет избыточного потребления памяти. Например, ошибка 719601 приводила к тому, что ячейка JavaScript содержала сотни мегабайт памяти, что гораздо больше, чем обычно.

- -

Избегайте написания медленных таблиц стилей CSS

- - - -

Избегайте использования технологии DOM Mutation Events

- -

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

- -

Используйте методы ленивой загрузки

- -

JavaScript-модуль XPCOMUtils предоставляет два метрода ленивой (отложенной) загрузки:

- - - -

Множество распространенных сервисов уже закэшированы для вас в модуле Services.jsm.

- -

Используйте ассинхронный ввод/вывод

- -

Это следует подчеркнуть: никогда не выполняйте синхронный ввод/вывод в главном потоке.

- -

Любой ввод/вывод в главном потоке, будь то активность жесткого диска или сетевая активность, может стать причиной серьезных проблем с временем отклика интерфейса пользователя.

- - - -

Избегайте событий перемещения мыши

- -

Избегайте использования обработчиков событий мыши, включая такие события, как mouseover, mouseout, mouseenter, mouseexit, и особенно mousemove. Они возникают довольно часто, поэтому их обработчики способны в значительной мере повысить нагрузку на процессор.

- -

Когда без них обойтись не получается, во время обработки события должен выполняться минимум вычислений, а существенная работа приостановлена. Обработчики должны добавляться к наиболее вероятному элементу, и удаляться, если непосредственно не требуются в данный момент.

- -

Избегайте анимированных изображений

- -

Анимированные изображения значительно более ресурсозатратны, чем считалось ранее, особенно когда используются в элементах {{ XULElem("tree") }}.

- -

Рассмотрите возможность применения Chrome Workers

- -

Вы можете использовать {{ domxref("ChromeWorker") }} для выполнения длительных задач или обработки данных.

- -

Смотрите также

- - -- cgit v1.2.3-54-g00ecf