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 --- 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 - 22 files changed, 4250 deletions(-) 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" (limited to 'files/ru/mozilla/add-ons/sdk') 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:

- - -- cgit v1.2.3-54-g00ecf