From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../mozilla/add-ons/add-on_guidelines/index.html | 121 +++++ files/ru/mozilla/add-ons/amo/index.html | 11 + files/ru/mozilla/add-ons/amo/policy/index.html | 22 + files/ru/mozilla/add-ons/code_snippets/index.html | 148 +++++ .../\320\272\321\203\320\272\320\270/index.html" | 36 ++ .../mozilla/add-ons/firefox_for_android/index.html | 82 +++ .../index.html | 395 ++++++++++++++ files/ru/mozilla/add-ons/index.html | 240 +++++++++ .../mozilla/add-ons/overlay_extensions/index.html | 65 +++ files/ru/mozilla/add-ons/sdk/guides/index.html | 365 +++++++++++++ .../index.html" | 519 ++++++++++++++++++ .../sdk/high-level_apis/addon-page/index.html | 32 ++ .../sdk/high-level_apis/context-menu/index.html | 578 ++++++++++++++++++++ .../mozilla/add-ons/sdk/high-level_apis/index.html | 10 + .../sdk/high-level_apis/passwords/index.html | 525 ++++++++++++++++++ files/ru/mozilla/add-ons/sdk/index.html | 90 ++++ .../mozilla/add-ons/sdk/low-level_apis/index.html | 23 + .../sdk/low-level_apis/places_bookmarks/index.html | 595 +++++++++++++++++++++ .../mozilla/add-ons/sdk/tools/console/index.html | 110 ++++ files/ru/mozilla/add-ons/sdk/tools/index.html | 10 + files/ru/mozilla/add-ons/sdk/tools/jpm/index.html | 497 +++++++++++++++++ .../sdk/tutorials/getting_started_(jpm)/index.html | 157 ++++++ files/ru/mozilla/add-ons/sdk/tutorials/index.html | 145 +++++ .../add-ons/sdk/tutorials/installation/index.html | 68 +++ .../creating_annotations/index.html" | 221 ++++++++ .../implementing_the_widget/index.html" | 68 +++ .../index.html" | 34 ++ .../overview/index.html" | 34 ++ .../index.html" | 94 ++++ .../index.html" | 61 +++ .../index.html" | 14 + .../anatomy_of_a_webextension/index.html | 148 +++++ .../webextensions/api/cookies/cookie/index.html | 107 ++++ .../add-ons/webextensions/api/cookies/index.html | 156 ++++++ .../add-ons/webextensions/api/downloads/index.html | 123 +++++ .../mozilla/add-ons/webextensions/api/index.html | 53 ++ .../api/runtime/getmanifest/index.html | 88 +++ .../add-ons/webextensions/api/runtime/index.html | 168 ++++++ .../add-ons/webextensions/api/tabs/get/index.html | 74 +++ .../add-ons/webextensions/api/tabs/hide/index.html | 79 +++ .../add-ons/webextensions/api/tabs/index.html | 179 +++++++ .../webextensions/api/webrequest/index.html | 188 +++++++ .../api/windows/createtype/index.html | 65 +++ .../add-ons/webextensions/api/windows/index.html | 106 ++++ .../chrome_incompatibilities/index.html | 331 ++++++++++++ .../webextensions/content_scripts/index.html | 495 +++++++++++++++++ .../content_security_policy/index.html | 111 ++++ .../add-ons/webextensions/examples/index.html | 34 ++ files/ru/mozilla/add-ons/webextensions/index.html | 109 ++++ .../intercept_http_requests/index.html | 155 ++++++ .../manifest.json/background/index.html | 115 ++++ .../content_security_policy/index.html | 117 ++++ .../manifest.json/description/index.html | 44 ++ .../webextensions/manifest.json/icons/index.html | 80 +++ .../add-ons/webextensions/manifest.json/index.html | 139 +++++ .../manifest.json/manifest_version/index.html | 45 ++ .../webextensions/manifest.json/name/index.html | 44 ++ .../manifest.json/permissions/index.html | 193 +++++++ .../webextensions/manifest.json/version/index.html | 49 ++ .../webextensions/match_patterns/index.html | 426 +++++++++++++++ .../add-ons/webextensions/prerequisites/index.html | 8 + .../user_interface/browser_action/index.html | 50 ++ .../user_interface/context_menu_items/index.html | 54 ++ .../user_interface/extension_pages/index.html | 73 +++ .../webextensions/user_interface/index.html | 107 ++++ .../user_interface/notifications/index.html | 51 ++ .../user_interface/omnibox/index.html | 68 +++ .../webextensions/user_interface/popups/index.html | 50 ++ .../user_interface/sidebars/index.html | 56 ++ .../what_are_webextensions/index.html | 95 ++++ .../your_first_webextension/index.html | 191 +++++++ .../your_second_webextension/index.html | 363 +++++++++++++ .../index.html" | 405 ++++++++++++++ .../index.html" | 238 +++++++++ .../index.html" | 218 ++++++++ .../index.html" | 353 ++++++++++++ .../index.html" | 102 ++++ 77 files changed, 11873 insertions(+) create mode 100644 files/ru/mozilla/add-ons/add-on_guidelines/index.html create mode 100644 files/ru/mozilla/add-ons/amo/index.html create mode 100644 files/ru/mozilla/add-ons/amo/policy/index.html create mode 100644 files/ru/mozilla/add-ons/code_snippets/index.html create mode 100644 "files/ru/mozilla/add-ons/code_snippets/\320\272\321\203\320\272\320\270/index.html" create mode 100644 files/ru/mozilla/add-ons/firefox_for_android/index.html create mode 100644 files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html create mode 100644 files/ru/mozilla/add-ons/index.html create mode 100644 files/ru/mozilla/add-ons/overlay_extensions/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/guides/index.html create 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" create mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/low-level_apis/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tools/console/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tools/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tools/jpm/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/index.html create mode 100644 files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html create 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" create 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" create 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" create 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" create 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" create 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" create mode 100644 "files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" create mode 100644 files/ru/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/cookies/cookie/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/cookies/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/downloads/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/runtime/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/tabs/get/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/tabs/hide/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/tabs/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/windows/createtype/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/api/windows/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/chrome_incompatibilities/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/content_scripts/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/content_security_policy/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/examples/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/intercept_http_requests/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/background/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/content_security_policy/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/description/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/icons/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/manifest_version/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/name/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/permissions/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/manifest.json/version/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/match_patterns/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/prerequisites/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/browser_action/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/notifications/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/omnibox/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/popups/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/user_interface/sidebars/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/what_are_webextensions/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/your_first_webextension/index.html create mode 100644 files/ru/mozilla/add-ons/webextensions/your_second_webextension/index.html create mode 100644 "files/ru/mozilla/add-ons/webextensions/\320\270\320\275\321\202\320\265\321\200\320\275\320\260\321\206\320\270\320\276\320\275\320\260\320\273\320\270\320\267\320\260\321\206\320\270\321\217/index.html" create mode 100644 "files/ru/mozilla/add-ons/webextensions/\320\274\320\276\320\264\320\270\321\204\320\270\320\272\320\260\321\206\320\270\321\217_\320\262\320\265\320\261_\321\201\321\202\321\200\320\260\320\275\320\270\321\206\321\213/index.html" create mode 100644 "files/ru/mozilla/add-ons/webextensions/\320\277\320\265\321\200\320\265\320\262\320\276\320\264/index.html" create mode 100644 "files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" create mode 100644 "files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" (limited to 'files/ru/mozilla/add-ons') diff --git a/files/ru/mozilla/add-ons/add-on_guidelines/index.html b/files/ru/mozilla/add-ons/add-on_guidelines/index.html new file mode 100644 index 0000000000..5be041195c --- /dev/null +++ b/files/ru/mozilla/add-ons/add-on_guidelines/index.html @@ -0,0 +1,121 @@ +--- +title: Add-on guidelines +slug: Mozilla/Add-ons/Add-on_guidelines +translation_of: 'https://extensionworkshop.com/documentation/publish/add-on-policies/' +--- +

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

+ +

Be Transparent

+ + + +

Be Respectful to Users

+ + + +

Be Safe

+ + + +

Be Stable

+ + + +

Exceptions

+ + + +

Other exceptions may apply.

+ +

Enforcement

+ +

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

+ +

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

+ +

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

+ +

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

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

{{AddonSidebar}}

+ +

Content to be added.

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

{{AddonSidebar}}

+ +

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

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

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

 

+ +
+

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

+ +

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

+ +

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

+ +

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

+ +

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

+
+ +

 

+ +

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

+ +

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

+ +

General

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

JavaScript libraries

+ +

Here are some JavaScript libraries that may come in handy.

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

Browser-oriented code

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

SVG

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

XUL Widgets

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

Windows-specific

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

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

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

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

+ +

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

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

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

+ + + +

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

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

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

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

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

+ +

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

+ + + +

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

+ +
+
+

Учебники

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

Образец кода

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

Справка по API

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

 

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

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

+
+ +

Requirements

+ +

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

+ +

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

+ +

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

+ +

Step 1: Use Services.jsm

+ +

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

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

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

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

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

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

+ +

Step 3a: Option 1: Use nsIZipReader

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

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

+ +

Step 3b: Option 2: Use XMLHttpRequest

+ +

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

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

Here's how to load a file using it:

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

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Step 4: Manually handle default preferences

+ +

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

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

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

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

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

+ +

Step 4a: Another way to handle default preferences

+ +

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

+ +

Step 5: No more internal JAR files

+ +

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

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

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

+ +

Why the internal JAR? Well, two reasons:

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

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

+ +

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

+ +

Step 6: No more XUL overlays

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

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

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

+ +

Step 7: Manually handle global CSS Stylesheets

+ +

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

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

Step 8: Window icons

+ +

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

+ +

Step 9: bootstrap.js

+ +

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

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

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

+ +

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

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

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

+ +

Step 10: Bypass cache when loading properties files

+ +

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

+ +

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

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

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

+ +

Put it all together

+ +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+
+ +

Further reading

+ + diff --git a/files/ru/mozilla/add-ons/index.html b/files/ru/mozilla/add-ons/index.html new file mode 100644 index 0000000000..067c5699bd --- /dev/null +++ b/files/ru/mozilla/add-ons/index.html @@ -0,0 +1,240 @@ +--- +title: Дополнения +slug: Mozilla/Add-ons +tags: + - NeedsTranslation + - TopicStub + - Дополнения + - Расширения +translation_of: Mozilla/Add-ons +--- +

Дополнения добавляют новые функциональные возможности в Gecko-приложения, такие, как Firefox, SeaMonkey и Thunderbird. Есть два основных типа дополнений: расширения, которые добавляют новые функции в приложение, и темы, изменяющие пользовательский интерфейс приложения.

+ +
+

Для расширений и тем в Mozilla работает хранилище на addons.mozilla.org, также известное как AMO. Когда вы помещаете дополнения на AMO, они рассматриваются, и после этого становятся доступны для пользователей. Вы не обязаны загружать свои дополнения в AMO, но если вы это сделаете, пользователи могут быть уверены в том, что они были предварительно проверены и будут знать, что ваше дополнение действительно полезно.

+
+ +

Дополнение может существенно повлиять на поведение приложения, на которое оно устанавливается. Мы разработали список советов, которые помогут вам удостовериться, что ваше дополнение будет приятным в использовании. Эти правила применяются для всех видов надстроек, независимо от того, размещены они на addons.mozilla.org или нет.

+ +
+

Расширения

+ +

Расширения добавляют новые функции к приложениям Mozilla, например таким как Firefox и Thunderbird. С их помощью можно изменить стандарное поведение браузера, например реализовать другой способ организации и управления вкладками. Можно даже изменять содержимое отображаемого веб приложения, чтобы улучшить удобство использования или например повысить безопасность определенных сайтов.

+ +

Существует 3 различных способа сборки расширений: restartless-расширения на основе Add-on SDK, restartless-расширения с реализацией этого механизма вручную (manually bootstrapped restartless extensions), и расширения с использованием технологии Overlay.

+ + + +
+

Технология WebExtensions

+ +

В данный момент мы разрабатываем систему под названием WebExtensions, которая будет новым способом разработки расширений для браузера Firefox, эта система будет гораздо более совместима с браузерами Chrome и Opera.

+ +

В будущем она станет наиболее предпочтительной при разработке новых проектов для браузера Firefox.

+В данный момент она является экспериментальной, но несмотря на это вы можете ознакомиться с документацией, если хотите ее опробовать.
+ +

Где это возможно, рекомендуется выбирать Add-On SDK, который использует механизм расширения без необходимости перезапуска браузера (restartless extensions), а также упрощает разработку и убирает за собой. Если Вам недостаточно возможностей комплекта средств разработки Add-on SDK для реализации ваших идей, механизм restartless Вы можете осуществить самостоятельно. Технология Overlay extensions в целом устарела и не рекомендуется при разработке новых расширений.

+ +

Для получения дополнительной информации о том, какой способ использовать, прочтите это сравнение.

+ +
+
+

Рекомендуемые практики

+ +

Вне зависимости от того, каким способом Вы разрабатываете расширение, имеются общие рекомендации, следуя которым вы гарантируете пользователю максимально приятную работу с вашим расширением.

+ +
+
Производительность
+
Убедитесь в том, что Ваше расширение обладает хорошей производительностью. Оно должно быть достаточно быстрым, иметь отзывчивый интерфейс и потреблять минимальный объем памяти.
+
Безопасность
+
Убедитесь в том, что Ваше приложение не подвергает пользователя опасности на вредоносных веб сайтах.
+
Этикет
+
Убедитесь в том, что Ваше расширение не конфликтует с другими расширениями.
+
+
+ +
+

Специфика разработки для различных приложений

+ +

Большая часть документации предполагает, что Вы разрабатываете для десктопной версии Firefox. Если Вы разрабатываете для других основанных на движке Gecko приложений, то существуют некоторые отличия, о которых Вам следует знать.

+ +
+
Thunderbird
+
Разработка расширений для почтового клиента Thunderbird.
+
Firefox для Андроид
+
Разработка расширений для Firefox под Андроид.
+
SeaMonkey
+
Разработка расширений для SeaMonkey.
+
+
+
+ +
+

Темы

+ +

Темы это дополнения, которые изменяют внешний вид пользовательского интерфейса.  Существуют два вида тем: легковесные темы и полные темы.

+ +
+
+

Легковесные темы значительно легче создать, чем полные, но их возможности ограничены.

+
+ +
+

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

+
+
+ +
+

Другие типы дополнений

+ +

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

+ +

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

+ +

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

+ +
    +
  1. Restartless extensions
  2. +
  3. Legacy extensions
  4. +
  5. Дополнения на основе SDK
  6. +
  7. Techniques +
      +
    1. Promises
    2. +
    +
  8. +
  9. Рекомендуемая практика +
      +
    1. Производительность
    2. +
    3. Безопасность
    4. +
    5. Этикет
    6. +
    +
  10. +
  11. Темы +
      +
    1. Легковесные темы
    2. +
    3. Легковесные темы FAQ
    4. +
    5. Полные темы
    6. +
    +
  12. +
  13. Legacy Plugins +
      +
    1. Plug-in Basics
    2. +
    3. Plug-in Development Overview
    4. +
    5. Initialization and Destruction
    6. +
    7. Drawing and Event Handling
    8. +
    9. Streams
    10. +
    11. URLs
    12. +
    13. Memory
    14. +
    15. Version, UI, and Status Information
    16. +
    17. Plug-in side Plug-in API +
        +
      1. NPP_Destroy
      2. +
      3. NPP_DestroyStream
      4. +
      5. NPP_GetValue
      6. +
      7. NP_GetValue
      8. +
      9. NPP_HandleEvent
      10. +
      11. NP_Initialize
      12. +
      13. NPP_New
      14. +
      15. NPP_NewStream
      16. +
      17. NPP_Print
      18. +
      19. NPP_SetValue
      20. +
      21. NPP_SetWindow
      22. +
      23. NP_Shutdown
      24. +
      25. NPP_StreamAsFile
      26. +
      27. NPP_URLNotify
      28. +
      29. NPP_Write
      30. +
      31. NPP_WriteReady
      32. +
      +
    18. +
    19. Browser Side Plug-in API +
        +
      1. NPN_DestroyStream
      2. +
      3. NPN_ForceRedraw
      4. +
      5. NPN_GetAuthenticationInfo
      6. +
      7. NPN_GetURL
      8. +
      9. NPN_GetURLNotify
      10. +
      11. NPN_GetValue
      12. +
      13. NPN_GetValueForURL
      14. +
      15. NPN_InvalidateRect
      16. +
      17. NPN_InvalidateRegion
      18. +
      19. NPN_MemAlloc
      20. +
      21. NPN_MemFlush
      22. +
      23. NPN_MemFree
      24. +
      25. NPN_NewStream
      26. +
      27. NPN_PluginThreadAsyncCall
      28. +
      29. NPN_PostURL
      30. +
      31. NPN_PostURLNotify
      32. +
      33. NPN_ReloadPlugins
      34. +
      35. NPN_RequestRead
      36. +
      37. NPN_SetValue
      38. +
      39. NPN_SetValueForURL
      40. +
      41. NPN_Status
      42. +
      43. NPN_UserAgent
      44. +
      45. NPN_Version
      46. +
      47. NPN_Write
      48. +
      +
    20. +
    21. Scripting plugins +
        +
      1. NPString
      2. +
      3. NPVariant
      4. +
      5. NPN_ReleaseVariantValue
      6. +
      7. NPN_GetStringIdentifier
      8. +
      9. NPN_GetStringIdentifiers
      10. +
      11. NPN_GetIntIdentifier
      12. +
      13. NPN_IdentifierIsString
      14. +
      15. NPN_UTF8FromIdentifier
      16. +
      17. NPN_IntFromIdentifier
      18. +
      19. NPObject
      20. +
      21. NPN_CreateObject
      22. +
      23. NPN_RetainObject
      24. +
      25. NPN_ReleaseObject
      26. +
      27. NPN_Invoke
      28. +
      29. NPN_InvokeDefault
      30. +
      31. NPN_Evaluate
      32. +
      33. NPN_GetProperty
      34. +
      35. NPN_SetProperty
      36. +
      37. NPN_RemoveProperty
      38. +
      39. NPN_HasProperty
      40. +
      41. NPN_HasMethod
      42. +
      43. NPN_SetException
      44. +
      45. NPClass
      46. +
      +
    22. +
    23. Structures
    24. +
    25. Constants
    26. +
    27. External Resources
    28. +
    +
  14. +
  15. Publishing add-ons +
      +
    1. Signing and distributing your add-on
    2. +
    3. Submit a new add-on
    4. +
    5. Policies +
        +
      1. Developer Agreement
      2. +
      3. Review Process
      4. +
      5. Add-on guidelines
      6. +
      7. Featured Add-ons
      8. +
      9. Contacting Us
      10. +
      +
    6. +
    +
  16. +
  17. Community and Support +
      +
    1. Add-ons Blog
    2. +
    3. Add-on Forums
    4. +
    5. Stack Overflow
    6. +
    7. Development Newsgroup
    8. +
    9. IRC Channel
    10. +
    +
  18. +
diff --git a/files/ru/mozilla/add-ons/overlay_extensions/index.html b/files/ru/mozilla/add-ons/overlay_extensions/index.html new file mode 100644 index 0000000000..ceac592b8d --- /dev/null +++ b/files/ru/mozilla/add-ons/overlay_extensions/index.html @@ -0,0 +1,65 @@ +--- +title: Overlay extensions +slug: Mozilla/Add-ons/Overlay_Extensions +tags: + - Add-ons + - Extensions + - Landing + - NeedsTranslation + - TopicStub +translation_of: Archive/Add-ons/Overlay_Extensions +--- +

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

+ + + +

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

+ +

Школа XUL

+ +

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

+ +

Ресурсы

+ +
+
+
+
Настройка среды
+
Настройка приложений для разработки расширений.
+
XUL
+
Учебники и справочники по языку программирования, используемому XUL-расширениями.
+
Примеры кода
+
Примеры кода, которые пригодятся.
+
Установка расширений
+
Как установить расширение копированием файлов в установочный каталог.
+
Руководство разработчика дополнений для Firefox
+
Руководство по разработка расширений.
+
JavaScript-модули, доступные разработчику
+
JavaScript-модули доступные разработчику расширений.
+
Настройка расширения
+
+
+ +
+
+
Как добавить свойства расширения, которые появятся в менеджере дополнений (Add-ons Manager).
+
FAQ
+
Решение некоторых общих проблем.
+
Сборка и установка расширения
+
Сборка и установка.
+
Создание бинарных расширений для Firefox
+
Создание бинарных расширений.
+
Создание расширения
+
Ещё один небольшой самоучитель по созданию расширения (только на русском языке)
+
Динамически изменяемый пользовательский интерфейс на XUL
+
В этой статье обсуждается управление XUL интерфейсами с использованием DOM и других API.
+
Настройка среды разработки расширений
+
В этой статье приводится несколько советов о том, как настроить ваше приложение Mozilla для удобной работы над расширениями.
+
Руководство по XUL
+
Руководство по XUL
+
+
+
diff --git a/files/ru/mozilla/add-ons/sdk/guides/index.html b/files/ru/mozilla/add-ons/sdk/guides/index.html new file mode 100644 index 0000000000..1eacaad55a --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/guides/index.html @@ -0,0 +1,365 @@ +--- +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" new file mode 100644 index 0000000000..59832331e8 --- /dev/null +++ "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" @@ -0,0 +1,519 @@ +--- +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 new file mode 100644 index 0000000000..069cb199b2 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html @@ -0,0 +1,32 @@ +--- +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 new file mode 100644 index 0000000000..2d88abc734 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html @@ -0,0 +1,578 @@ +--- +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 new file mode 100644 index 0000000000..32b39d045b --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html @@ -0,0 +1,10 @@ +--- +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 new file mode 100644 index 0000000000..535385e895 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html @@ -0,0 +1,525 @@ +--- +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 new file mode 100644 index 0000000000..6c8217da66 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/index.html @@ -0,0 +1,90 @@ +--- +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 new file mode 100644 index 0000000000..8cd08458f0 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html @@ -0,0 +1,23 @@ +--- +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 new file mode 100644 index 0000000000..299e234fb2 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html @@ -0,0 +1,595 @@ +--- +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 new file mode 100644 index 0000000000..d28b31d127 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tools/console/index.html @@ -0,0 +1,110 @@ +--- +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 new file mode 100644 index 0000000000..b55c672f17 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tools/index.html @@ -0,0 +1,10 @@ +--- +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 new file mode 100644 index 0000000000..dbfacde500 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html @@ -0,0 +1,497 @@ +--- +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 new file mode 100644 index 0000000000..d9453e9767 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html @@ -0,0 +1,157 @@ +--- +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 new file mode 100644 index 0000000000..277c5573d9 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tutorials/index.html @@ -0,0 +1,145 @@ +--- +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 new file mode 100644 index 0000000000..48b8923923 --- /dev/null +++ b/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html @@ -0,0 +1,68 @@ +--- +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" new file mode 100644 index 0000000000..07cecddaf5 --- /dev/null +++ "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" @@ -0,0 +1,221 @@ +--- +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" new file mode 100644 index 0000000000..ef43991658 --- /dev/null +++ "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" @@ -0,0 +1,68 @@ +--- +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" new file mode 100644 index 0000000000..eab37823c0 --- /dev/null +++ "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" @@ -0,0 +1,34 @@ +--- +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" new file mode 100644 index 0000000000..08e4713b33 --- /dev/null +++ "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" @@ -0,0 +1,34 @@ +--- +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" new file mode 100644 index 0000000000..7b6e8bf507 --- /dev/null +++ "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" @@ -0,0 +1,94 @@ +--- +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" new file mode 100644 index 0000000000..d0ab8d6f79 --- /dev/null +++ "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" @@ -0,0 +1,61 @@ +--- +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" new file mode 100644 index 0000000000..987a420410 --- /dev/null +++ "b/files/ru/mozilla/add-ons/sdk/\320\277\321\200\320\276\320\261\320\260/index.html" @@ -0,0 +1,14 @@ +--- +title: Builder +slug: Mozilla/Add-ons/SDK/проба +translation_of: Archive/Add-ons/Add-on_SDK/Builder +--- +

The Add-on Builder was a web-based development environment that allowed developers to create add-ons using the SDK APIs, but without needing to use the cfx command line tool. It was retired on April 1, 2014, and the "builder.addons.mozilla.org" domain now redirects to this page.
+
+ If you have only used the SDK through the Builder, you already know most of what you need to know to develop using just the SDK. The high-level and low-level APIs used for Builder add-ons are exactly the same for Builder and SDK. To switch to the SDK:

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/ru/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html new file mode 100644 index 0000000000..3ca9e8bae6 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html @@ -0,0 +1,148 @@ +--- +title: Анатомия Расширения +slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +tags: + - Расширение + - веб расширение +translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +--- +

{{AddonSidebar}}

+ +

Расширение состоит из набора файлов, упакованных для распространения и установки. В этой статье мы быстро рассмотрим файлы, которые могут присутствовать в расширении.

+ +

manifest.json

+ +

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

+ +

Этот манифест также может содержать указатели на несколько других типов файлов:

+ + + +


+

+ +

Для получения подробной информации см. справочную страницу  manifest.json

+ +

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

+ +

Фоновые скрипты

+ +

Расширения часто должны поддерживать долгосрочное состояние или выполнять долгосрочные операции независимо от срока жизни любой конкретной веб-страницы или окна браузера. Для этого нужны фоновые сценарии.

+ +

Фоновые сценарии загружаются сразу после загрузки расширения и остаются загруженными до тех пор, пока расширение не будет отключено или удалено. Вы можете использовать любой API расширений в сценарии, если вы запросили необходимые разрешения.

+ +

Спецификации фоновых скриптов

+ +

Вы можете включить фоновый скрипт, используя background ключ в «manifest.json»:

+ +
// manifest.json
+
+"background": {
+  "scripts": ["background-script.js"]
+}
+ +

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

+ +

Вместо указания несколько фоновых сценариев выможете указать фоновую страницу, которая так же преимущества поддержки ES6 модулей:

+ +

manifest.json

+ +
// manifest.json
+
+"background": {
+  "page": "background-page.html"
+}
+ +

background-page.html

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <script type="module" src="background-script.js"></script>
+  </head>
+</html>
+ +

Окружение фоновых скриптов

+ +

DOM APIs

+ +

Фоновые скрипты запускаются в пространстве специальной страницы, называемой фоновой. Это дает им доступ к глобальному window объекту, а так же ко всем его DOM APIs.

+ +

WebExtension APIs

+ +

Фоновые скрипты могут использовать любые API расширений, если расширение имеет необходимые разрешения.

+ +

Многоцелевой доступ

+ +

Фоновые скрипты могут осуществлять XHR запросы к любому домену, если расширение имеет host разрешения.

+ +

Web-содержимое

+ +

Фоновые скрипты не получают прямого доступа к веб-страницам. Однако они могут загружать скрипты содержимого на веб-страницы и взаимодействовать с этими скриптами с помощью API передачи сообщений.

+ +

Политика безопастности содержимого

+ +

Фоновые скрипты ограничены в выполнении потенциально опасных операций, таких как eval(), через политику безопасности содержимого. Подробнее см. Content Security Policy.

+ +

Боковые панели (sidebar), всплывающие окна (popup), страницы настроек

+ +

Ваше расширение может иметь разнообразные компоненты интерфейса, определённые в HTML документах:

+ + + +

Для каждого из этих компонентов вы создаете HTML файл и помещаете специальную информацию в manifest.json. HTML файл может в себя включать CSS и JavaScript файлы, как и любая web-страница.

+ +

Всё это типы веб-страниц расширения, и, в отличие от нормальных веб-страниц, ваш JavaScript может использовать все привелегии WebExtension APIs, как и ваши фоновые скрипты. Они даже могут получить доступ к переменным в фоновой странице, используя {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

+ +

Веб-страницы расширения

+ +

Вы также можете включить HTML документы в ваше расширение, даже если они не будут включены в какой-либо существующий компонент пользовательского интерфейса. В отличие от документов, которые вы можете предоставить для боковых панелей, всплывающих окон или страниц настроек, эти документы не содержатся в manifest.json. Однако, они также имеют такой же доступ к WebExtension APIs, как и фоновые скрипты.

+ +

Вы можете загрузить такую страницу, используя {{WebExtAPIRef("windows.create()")}} или {{WebExtAPIRef("tabs.create()")}}.

+ +

Подробнее см. Extension pages.

+ +

Встраиваемые скрипты

+ +

Используйте встраиваемые скрипты для доступа и изменения веб-страниц. Встраиваемые скрипты загружаются в веб-страницу и исполняются в контексте данной конкретной страницы.

+ +

Встраиваемые скрипты предоставляются расширением; этим они отличаются от скриптов, загруженных самой веб-страницей, включая тех, что загружены с помощью {{HTMLElement("script")}} элемента веб-страницы.

+ +

Встраиваемые скрипты имеют доступ и могут манипулировать DOM, как и обычные скрипты, загруженные веб-страницей.

+ +

В отличие от обычных скриптов, они могут:

+ + + +

Встраиваемые скрипты не могут напрямую взаимодействовать с обычными скриптами на странице, но они могут обмениваться сообщениями с помощью стандартного window.postMessage() API.

+ +

Обычно, когда мы говорим о встраиваемых скриптах, мы отсылаемся к JavaScript, но вы так же можете внедрить CSS в веб-страницы, используя этот же механизм.

+ +

Подробнее см. content scripts.

+ +

Веб-доступные ресурсы

+ +

Веб-доступные ресурсы - это ресурсы вроде изображений, HTML, CSS и JavaScript, которые вы включаете в расширение и хотите сделать доступными для встраиваемых скриптов и оригинальных скриптов веб-страницы. Такие ресурсы могут быть доступны скриптам через специальную URI схему.

+ +

Например, если встраиваемый скрипт хочет добавить какие-либо изображения в веб-страницу, вы можете включить эти изображения в расширение и сделать их веб-доступными. Тогда встраиваемый скрипт может создать и добавить img тэги, которые будут ссылаться на эти изображения через src атрибут.

+ +

Подробнее см. web_accessible_resources секцию manifest.json.

+ +

 

+ +

 

diff --git a/files/ru/mozilla/add-ons/webextensions/api/cookies/cookie/index.html b/files/ru/mozilla/add-ons/webextensions/api/cookies/cookie/index.html new file mode 100644 index 0000000000..9191b3017a --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/cookies/cookie/index.html @@ -0,0 +1,107 @@ +--- +title: cookies.Cookie +slug: Mozilla/Add-ons/WebExtensions/API/cookies/Cookie +tags: + - API + - Cookies + - cookie + - Дополнения + - Расширения + - Справка + - данные +translation_of: Mozilla/Add-ons/WebExtensions/API/cookies/Cookie +--- +
{{AddonSidebar()}}
+ +

Тип Cookie из {{WebExtAPIRef("cookies")}} API представляет собой информацию о HTTP cookie.

+ +

Тип

+ +

Значения этого типа - объекты, которые могут содержать следующие свойства:

+ +
+
name
+
string - содержит имя cookie.
+
value
+
string - содержит значение cookie.
+
domain
+
string - содержит домен, которому принадлежит cookie (например, "www.google.com", "example.com").
+
hostOnly
+
boolean - true если cookie является host-only (то есть запрашивающий хост должен в точности совпадать с доменом cookie), в ином случае false.
+
path
+
string - содержит path cookie.
+
secure
+
boolean - true, если cookie помечен как secure (то есть его область действия ограничена безопасными каналами, обычно HTTPS), в ином случае false.
+
httpOnly
+
boolean - true если cookie помечен как HttpOnly (то есть он недоступен для клиентских скриптов), иначе false.
+
session
+
boolean - true если cookie является сессионным, false если cookie является постоянным с указанным временем жизни.
+
expirationDate{{optional_inline}}
+
number - содержит срок годности cookie, который представляется количеством секунд с начала UNIX-эры. Отсутствует для сессионных cookie.
+
storeId
+
string - представляет собой ID хранилища, в котором хранится данный cookie, как указано в соответствии с {{WebExtAPIRef("cookies.getAllCookieStores()")}}.
+
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.api.cookies.Cookie")}}

+ +

Примеры

+ +

В большинстве методов из cookies API объекты типа Cookie используются как входные параметры методов, либо же как возвращаемые значения. К примеру, вызов {{WebExtAPIRef("cookies.getAll()")}} возвращает массив объектов типа Cookie.

+ +

В примере ниже мы запрашиваем все cookie, а затем выводим в лог некоторые из полей полученных Cookie объектов:

+ +
function logCookies(cookies) {
+  for (cookie of cookies) {
+    console.log(`Domain: ${cookie.domain}`);
+    console.log(`Name: ${cookie.name}`);
+    console.log(`Value: ${cookie.value}`);
+    console.log(`Persistent: ${!cookie.session}`);
+  }
+}
+
+var gettingAll = browser.cookies.getAll({});
+gettingAll.then(logCookies);
+ +

{{WebExtExamples}}

+ +
Примечание + +

Это API основано на API Chromiumа chrome.cookies. Эта документация основана на cookies.json из кода Chromium.

+ +

Информация о совместимости Microsoft Edge предоставлена корпорацией Microsoft и включена здесь под лицензией Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/cookies/index.html b/files/ru/mozilla/add-ons/webextensions/api/cookies/index.html new file mode 100644 index 0000000000..a31f300edf --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/cookies/index.html @@ -0,0 +1,156 @@ +--- +title: cookies +slug: Mozilla/Add-ons/WebExtensions/API/cookies +tags: + - API + - Add-ons + - Cookies + - Extensions + - Interface + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API/cookies +--- +
{{AddonSidebar}}
+ +

Позволяет  WebExtensions получить и установить куки ,а также сообщить об их изменении.

+ +

Для использования этого API,вам нужно предоставить доступ  API permission в вашем файле manifest.json,а также  host permissions для тех сайтов чьи куки вам нужны для доступа.Смотрите cookie Permissions.

+ +

Types

+ +
+
{{WebExtAPIRef("cookies.Cookie")}}
+
Предоставляет информацию о HTTP cookie
+
{{WebExtAPIRef("cookies.CookieStore")}}
+
Represents a cookie store in the browser.
+
{{WebExtAPIRef("cookies.OnChangedCause")}}
+
Represents the reason a cookie changed.
+
+ +

Methods

+ +
+
{{WebExtAPIRef("cookies.get()")}}
+
Запрашивает информацию об одном кукис.
+
{{WebExtAPIRef("cookies.getAll()")}}
+
Выдает все кукис которые подходят установленному фильтру.
+
{{WebExtAPIRef("cookies.set()")}}
+
Устанавливает кукис с заданной информацией;в том случае если подобный кукис был информация будет перезаписана.
+
{{WebExtAPIRef("cookies.remove()")}}
+
Удаляет кукис по имени.
+
{{WebExtAPIRef("cookies.getAllCookieStores()")}}
+
Список всех существующих куки
+
+ +

Event handlers

+ +
+
{{WebExtAPIRef("cookies.onChanged")}}
+
Происходит когда кукис задается или меняется.
+
+ +

Permissions

+ +

In order to use this API, an add-on must specify the "cookies" API permission in its manifest, along with host permissions for any sites for which it wishes to access cookies. The add-on may read or write any cookies which could be read or written by a URL matching the host permissions. For example:

+ +
+
http://*.example.com/
+
+

An add-on with this host permission may:

+ +
    +
  • Read a non-secure cookie for www.example.com, with any path.
  • +
  • Write a secure or non-secure cookie for www.example.com, with any path.
  • +
+ +

It may not:

+ +
    +
  • Read a secure cookie for www.example.com.
  • +
+
+
http://www.example.com/
+
+

An add-on with this host permission may:

+ +
    +
  • Read a non-secure cookie for www.example.com, with any path.
  • +
  • Read a non-secure cookie for .example.com, with any path.
  • +
  • Write a secure or non-secure cookie for www.example.com with any path.
  • +
  • Write a secure or non-secure cookie for .example.com with any path.
  • +
+ +

It may not:

+ +
    +
  • Read or write a cookie for foo.example.com.
  • +
  • Read or write a cookie for foo.www.example.com.
  • +
+
+
*://*.example.com/
+
+

An add-on with this host permission may:

+ +
    +
  • Read or write a secure or non-secure cookie for www.example.com with any path.
  • +
+
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.cookies")}}

+ + + +

Edge incompatibilities

+ +

Promises are not supported in Edge. Use callbacks instead.

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.cookies API. This documentation is derived from cookies.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/downloads/index.html b/files/ru/mozilla/add-ons/webextensions/api/downloads/index.html new file mode 100644 index 0000000000..735dab43d5 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/downloads/index.html @@ -0,0 +1,123 @@ +--- +title: downloads +slug: Mozilla/Add-ons/WebExtensions/API/downloads +translation_of: Mozilla/Add-ons/WebExtensions/API/downloads +--- +
{{AddonSidebar}}
+ +

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

+ +

Для использования этого API вам необходимо указать "downloads" API permission в вашем manifest.json файле.

+ +

Types

+ +
+
{{WebExtAPIRef("downloads.FilenameConflictAction")}}
+
Определяет действия в случае, если имя загружаемого файла конфликтует с именем существующего файла.
+
{{WebExtAPIRef("downloads.InterruptReason")}}
+
Defines a set of possible reasons why a download was interrupted.
+
{{WebExtAPIRef("downloads.DangerType")}}
+
Defines a set of common warnings of possible dangers associated with downloadable files.
+
{{WebExtAPIRef("downloads.State")}}
+
Defines different states that a current download can be in.
+
{{WebExtAPIRef("downloads.DownloadItem")}}
+
Represents a downloaded file.
+
{{WebExtAPIRef("downloads.StringDelta")}}
+
Represents the difference between two strings.
+
{{WebExtAPIRef("downloads.DoubleDelta")}}
+
Represents the difference between two doubles.
+
{{WebExtAPIRef("downloads.BooleanDelta")}}
+
Represents the difference between two booleans.
+
{{WebExtAPIRef("downloads.DownloadTime")}}
+
Represents the time a download took to complete.
+
{{WebExtAPIRef("downloads.DownloadQuery")}}
+
Defines a set of parameters that can be used to search the downloads manager for a specific set of downloads.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("downloads.download()")}}
+
Downloads a file, given its URL and other optional preferences.
+
{{WebExtAPIRef("downloads.search()")}}
+
Queries the {{WebExtAPIRef("downloads.DownloadItem", "DownloadItems")}} available in the browser's downloads manager, and returns those that match the specified search criteria.
+
{{WebExtAPIRef("downloads.pause()")}}
+
Pauses a download.
+
{{WebExtAPIRef("downloads.resume()")}}
+
Resumes a paused download.
+
{{WebExtAPIRef("downloads.cancel()")}}
+
Cancels a download.
+
{{WebExtAPIRef("downloads.getFileIcon()")}}
+
Retrieves an icon for the specified download.
+
{{WebExtAPIRef("downloads.open()")}}
+
Opens the downloaded file with its associated application.
+
{{WebExtAPIRef("downloads.show()")}}
+
Opens the platform's file manager application to show the downloaded file in its containing folder.
+
{{WebExtAPIRef("downloads.showDefaultFolder()")}}
+
Opens the platform's file manager application to show the default downloads folder.
+
{{WebExtAPIRef("downloads.erase()")}}
+
Erases matching {{WebExtAPIRef("downloads.DownloadItem", "DownloadItems")}} from the browser's download history, without deleting the downloaded files from disk.
+
{{WebExtAPIRef("downloads.removeFile()")}}
+
Removes a downloaded file from disk, but not from the browser's download history.
+
{{WebExtAPIRef("downloads.acceptDanger()")}}
+
Prompts the user to accept or cancel a dangerous download.
+
{{WebExtAPIRef("downloads.drag()")}}
+
Initiates dragging the downloaded file to another application.
+
{{WebExtAPIRef("downloads.setShelfEnabled()")}}
+
Enables or disables the gray shelf at the bottom of every window associated with the current browser profile. The shelf will be disabled as long as at least one extension has disabled it.
+
+ +

Events

+ +
+
{{WebExtAPIRef("downloads.onCreated")}}
+
Fires with the {{WebExtAPIRef("downloads.DownloadItem", "DownloadItem")}} object when a download begins.
+
{{WebExtAPIRef("downloads.onErased")}}
+
Fires with the downloadId when a download is erased from history.
+
{{WebExtAPIRef("downloads.onChanged")}}
+
When any of a {{WebExtAPIRef("downloads.DownloadItem", "DownloadItem")}}'s properties except bytesReceived changes, this event fires with the downloadId and an object containing the properties that changed.
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.downloads")}}

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.downloads API.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/index.html b/files/ru/mozilla/add-ons/webextensions/api/index.html new file mode 100644 index 0000000000..6fcf34ce28 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/index.html @@ -0,0 +1,53 @@ +--- +title: JavaScript APIs +slug: Mozilla/Add-ons/WebExtensions/API +tags: + - Web-расширение + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/API +--- +
{{AddonSidebar}}
+ +
+

WebExtension JavaScript API может быть использован в фоновых скриптах расширения, а так же в любых других документах, поставляемых вместе с расширением, таких как  документы во всплывающих окнах после нажатия кнопок активации расширения browser action на панели инструментов или page action в строке адреса, боковой панели, страницах настроек или новых открытых вкладках. Некоторые из этих API могут быть доступны на встраиваемых в страницу скриптах (см. список в руководстве по встраиваемым скриптам).

+ +

Для использования отдельных более продвинутых API, необходимо запросить разрешения в manifest.json вашего дополнения.

+ +

Вы можете получить доступ к API, используя пространство имён browser:

+ +
function logTabs(tabs) {
+  console.log(tabs);
+}
+
+browser.tabs.query({currentWindow: true}, logTabs);
+
+ +
+

Многие API выполняются асинхронно, возвращая Promise:

+ +
function logCookie(c) {
+  console.log(c);
+}
+
+function logError(e) {
+  console.error(e);
+}
+
+var setCookie = browser.cookies.set(
+  {url: "/"}
+);
+setCookie.then(logCookie, logError);
+
+ +
Обратите внимание, что это отличается от расширений Google Chrome, которые используют пространство имён chrome вместо browser и колбэки для асинхронных функций вместо промисов. + +

Для поддержки портирования, реализация Firefox WebExtensions API так же поддерживает пространство имён chrome и использование колбэков. Это позволяет в большинстве случаев не изменять код, изначально написанный для Chrome.

+ +

Mozilla так же предоставляет полифилл, который позволяет коду, использующему browser и промисы, работать без изменений в Chrome: https://github.com/mozilla/webextension-polyfill.

+ +

Microsoft Edge использует пространство имен browser, но ещё не поддерживает, основанный на промисах асинхронный API. В Edge на данный момент асинхронные вызовы API должны использовать колбэки.

+ +

Не все браузеры поддерживают все API: детали см. Browser support for JavaScript APIs.

+
+ +
{{SubpagesWithSummaries}}
diff --git a/files/ru/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html b/files/ru/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html new file mode 100644 index 0000000000..f506e54335 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/runtime/getmanifest/index.html @@ -0,0 +1,88 @@ +--- +title: runtime.getManifest() +slug: Mozilla/Add-ons/WebExtensions/API/runtime/getManifest +tags: + - API + - Reference + - WebExtensions + - getManifest + - runtime + - Веб-расширения + - Дополнения + - Нестандартный + - Расширения + - Ссылка + - метод +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/getManifest +--- +
{{AddonSidebar()}}
+ +
Получить весь файл manifest.json в виде объекта JavaScript, совместимого с JSON.
+ +
+ +

Синтаксис

+ +
browser.runtime.getManifest()
+
+ +

Параметры

+ +

Нет.

+ +

Возвращаемое значение

+ +

object - объект JSON, представляющий манифест.

+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.api.runtime.getManifest")}}

+ +

Примеры

+ +

Получить манифест и вывести его свойство "name":

+ +
var manifest = browser.runtime.getManifest();
+console.log(manifest.name);
+ +

{{WebExtExamples}}

+ +
Справка + +

Этот API основан на API Chromium chrome.runtime. Настоящая документация унаследована от  runtime.json в коде Chromium.

+ +

Данные о совместимости Microsoft Edge предоставлены Корпорацией Microsoft и включены сюда под лицензией Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/runtime/index.html b/files/ru/mozilla/add-ons/webextensions/api/runtime/index.html new file mode 100644 index 0000000000..62478e3457 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/runtime/index.html @@ -0,0 +1,168 @@ +--- +title: runtime +slug: Mozilla/Add-ons/WebExtensions/API/runtime +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Reference + - TopicStub + - WebExtensions + - runtime +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime +--- +
{{AddonSidebar}}
+ +

This module provides information about your extension and the environment it's running in.

+ +

It also provides messaging APIs enabling you to:

+ + + +

Types

+ +
+
{{WebExtAPIRef("runtime.Port")}}
+
Represents one end of a connection between two specific contexts, which can be used to exchange messages.
+
{{WebExtAPIRef("runtime.MessageSender")}}
+
+

Contains information about the sender of a message or connection request.

+
+
{{WebExtAPIRef("runtime.PlatformOs")}}
+
Identifies the browser's operating system.
+
{{WebExtAPIRef("runtime.PlatformArch")}}
+
Identifies the browser's processor architecture.
+
{{WebExtAPIRef("runtime.PlatformInfo")}}
+
Contains information about the platform the browser is running on.
+
{{WebExtAPIRef("runtime.RequestUpdateCheckStatus")}}
+
Result of a call to {{WebExtAPIRef("runtime.requestUpdateCheck()")}}.
+
{{WebExtAPIRef("runtime.OnInstalledReason")}}
+
The reason that the {{WebExtAPIRef("runtime.onInstalled")}} event is being dispatched.
+
{{WebExtAPIRef("runtime.OnRestartRequiredReason")}}
+
The reason that the {{WebExtAPIRef("runtime.onRestartRequired")}} event is being dispatched.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("runtime.lastError")}}
+
This value is set when an asynchronous function has an error condition that it needs to report to its caller.
+
{{WebExtAPIRef("runtime.id")}}
+
The ID of the extension.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("runtime.getBackgroundPage()")}}
+
Retrieves the Window object for the background page running inside the current extension.
+
{{WebExtAPIRef("runtime.openOptionsPage()")}}
+
+

Opens your extension's options page.

+
+
{{WebExtAPIRef("runtime.getManifest()")}}
+
Gets the complete manifest.json file, serialized as an object.
+
{{WebExtAPIRef("runtime.getURL()")}}
+
Given a relative path from the manifest.json to a resource packaged with the extension, returns a fully-qualified URL.
+
{{WebExtAPIRef("runtime.setUninstallURL()")}}
+
Sets a URL to be visited when the extension is uninstalled.
+
{{WebExtAPIRef("runtime.reload()")}}
+
Reloads the extension.
+
{{WebExtAPIRef("runtime.requestUpdateCheck()")}}
+
Checks for updates to this extension.
+
{{WebExtAPIRef("runtime.connect()")}}
+
Establishes a connection from a content script to the main extension process, or from one extension to a different extension.
+
{{WebExtAPIRef("runtime.connectNative()")}}
+
+
Connects the extension to a native application on the user's computer.
+
+
{{WebExtAPIRef("runtime.sendMessage()")}}
+
Sends a single message to event listeners within your extension or a different extension. Similar to {{WebExtAPIRef('runtime.connect')}} but only sends a single message, with an optional response.
+
{{WebExtAPIRef("runtime.sendNativeMessage()")}}
+
Sends a single message from an extension to a native application.
+
{{WebExtAPIRef("runtime.getPlatformInfo()")}}
+
Returns information about the current platform.
+
{{WebExtAPIRef("runtime.getBrowserInfo()")}}
+
Returns information about the browser in which this extension is installed.
+
{{WebExtAPIRef("runtime.getPackageDirectoryEntry()")}}
+
Returns a DirectoryEntry for the package directory.
+
+ +

Events

+ +
+
{{WebExtAPIRef("runtime.onStartup")}}
+
Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started.
+
{{WebExtAPIRef("runtime.onInstalled")}}
+
Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.
+
{{WebExtAPIRef("runtime.onSuspend")}}
+
Sent to the event page just before the extension is unloaded. This gives the extension an opportunity to do some cleanup.
+
{{WebExtAPIRef("runtime.onSuspendCanceled")}}
+
Sent after {{WebExtAPIRef("runtime.onSuspend")}} to indicate that the extension won't be unloaded after all.
+
{{WebExtAPIRef("runtime.onUpdateAvailable")}}
+
Fired when an update is available, but isn't installed immediately because the extension is currently running.
+
{{WebExtAPIRef("runtime.onBrowserUpdateAvailable")}} {{deprecated_inline}}
+
Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.
+
{{WebExtAPIRef("runtime.onConnect")}}
+
Fired when a connection is made with either an extension process or a content script.
+
{{WebExtAPIRef("runtime.onConnectExternal")}}
+
Fired when a connection is made with another extension.
+
{{WebExtAPIRef("runtime.onMessage")}}
+
Fired when a message is sent from either an extension process or a content script.
+
{{WebExtAPIRef("runtime.onMessageExternal")}}
+
Fired when a message is sent from another extension. Cannot be used in a content script.
+
{{WebExtAPIRef("runtime.onRestartRequired")}}
+
Fired when the device needs to be restarted.
+
+ +

Browser compatibility

+ + + +

{{Compat("webextensions.api.runtime")}}

+ +
{{WebExtExamples("h2")}}
+ +
Acknowledgements + +

This API is based on Chromium's chrome.runtime API. This documentation is derived from runtime.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/tabs/get/index.html b/files/ru/mozilla/add-ons/webextensions/api/tabs/get/index.html new file mode 100644 index 0000000000..25a2126d65 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/tabs/get/index.html @@ -0,0 +1,74 @@ +--- +title: tabs.get() +slug: Mozilla/Add-ons/WebExtensions/API/tabs/get +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs/get +--- +
{{AddonSidebar()}}
+ +

Получает сведения об указанной вкладке.

+ +

Синтаксис

+ +
browser.tabs.get(
+  tabId,              // integer
+  function(tab) {...} // function
+)
+
+ +

Параметры

+ +
+
tabId
+
integer.
+
callback
+
function. Функция принимает следующие аргументы: +
+
tab
+
{{WebExtAPIRef('tabs.Tab')}}.
+
+
+
+ +

Совместимость с браузерами

+ +

{{Compat("webextensions.api.tabs.get")}}

+ +

Примеры

+ +

{{WebExtExamples}}

+ +
Благодарность + +

Этот API основан на Chromium chrome.tabs API. Это документация получена из tabs.json в коде Chromium.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/tabs/hide/index.html b/files/ru/mozilla/add-ons/webextensions/api/tabs/hide/index.html new file mode 100644 index 0000000000..a91d67f008 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/tabs/hide/index.html @@ -0,0 +1,79 @@ +--- +title: tabs.hide() +slug: Mozilla/Add-ons/WebExtensions/API/tabs/hide +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs/hide +--- +
{{AddonSidebar()}}
+ +

Hides one or more tabs.

+ +

Hidden tabs are no longer visible in the browser's tabstrip. Hidden tabs are not automatically discarded: the code running in them continues to run. You can explicitly discard tabs whenever you hide them: although this is not appropriate in all situations, it will help to reduce the resources used by the browser.

+ +

This is an asynchronous function that returns a Promise.

+ +

Not all tabs are eligible for being hidden:

+ + + +

The first time an extension hides a tab, the browser will tell the user that the tab is being hidden, show them how they can access the hidden tab, and give them the option of disabling the extension instead.

+ +

To use this API you must have the "tabHide" permission.

+ +

Syntax

+ +
var hiding = browser.tabs.hide(
+  tabIds          // integer or integer array
+)
+
+ +

Parameters

+ +
+
tabIds
+
integer or array of integer. The IDs of the tab or tabs to hide.
+
If any of these tabs are not eligible for being hidden, they will not be hidden, but the call will still succeed and eligible tabs will still be hidden. For example, if you pass [1, 3], and 1 identifies the active tab, then only 3 will be hidden.
+
However, if any of the tab IDs are invalid, the call will fail and no tabs will be hidden.
+
+ +

Return value

+ +

A Promise that will be fulfilled with an array containing the IDs of the tabs that were hidden. If any error occurs, the promise will be rejected with an error message.

+ +

Browser compatibility

+ + + +

{{Compat("webextensions.api.tabs.hide")}}

+ +

Examples

+ +

Hide a single tab:

+ +
function onHidden() {
+  console.log(`Hidden`);
+}
+
+function onError(error) {
+  console.log(`Error: ${error}`);
+}
+
+browser.tabs.hide(2).then(onHidden, onError);
+ +

Hide multiple tabs:

+ +
function onHidden() {
+  console.log(`Hidden`);
+}
+
+function onError(error) {
+  console.log(`Error: ${error}`);
+}
+
+browser.tabs.hide([15, 14, 1]).then(onHidden, onError);
+ +

{{WebExtExamples}}

diff --git a/files/ru/mozilla/add-ons/webextensions/api/tabs/index.html b/files/ru/mozilla/add-ons/webextensions/api/tabs/index.html new file mode 100644 index 0000000000..696329aa4f --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/tabs/index.html @@ -0,0 +1,179 @@ +--- +title: tabs +slug: Mozilla/Add-ons/WebExtensions/API/tabs +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebExtensions + - tabs +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs +--- +
{{AddonSidebar}}
+ +

Interact with the browser's tab system. You can use this API to get a list of opened tabs and to create, modify, and rearrange tabs in the browser.

+ +

You can use most of this API without any special permission. However, to access Tab.url, Tab.title, and Tab.faviconUrl, you need to have the "tabs" permission. In Firefox this also means you need "tabs" to {{WebExtAPIRef("tabs.query", "query")}} by URL.

+ +

Types

+ +
+
{{WebExtAPIRef("tabs.MutedInfoReason")}}
+
An event that caused a muted state change.
+
{{WebExtAPIRef("tabs.MutedInfo")}}
+
Tab muted state and the reason for the last state change.
+
{{WebExtAPIRef("tabs.Tab")}}
+
Contains various properties of a single tab.
+
{{WebExtAPIRef("tabs.ZoomSettingsMode")}}
+
Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; defaults to automatic.
+
{{WebExtAPIRef("tabs.ZoomSettingsScope")}}
+
Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to per-origin when in automatic mode, and per-tab otherwise.
+
{{WebExtAPIRef("tabs.ZoomSettings")}}
+
Defines how zoom changes in a tab are handled and at what scope.
+
{{WebExtAPIRef("tabs.TabStatus")}}
+
Whether the tabs have completed loading.
+
{{WebExtAPIRef("tabs.WindowType")}}
+
The type of window.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("tabs.TAB_ID_NONE")}}
+
An ID which represents the absence of a browser tab.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("tabs.get()")}}
+
Retrieves details about the specified tab.
+
{{WebExtAPIRef("tabs.getCurrent()")}}
+
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
+
{{WebExtAPIRef("tabs.connect()")}}
+
Connects to the content script(s) in the specified tab. The {{WebExtAPIRef('runtime.onConnect')}} event is fired in each content script running in the specified tab for the current extension. For more details, see content script messaging.
+
{{WebExtAPIRef("tabs.sendRequest()")}}
+
Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The {{WebExtAPIRef('extension.onRequest')}} event is fired in each content script running in the specified tab for the current extension.
+
{{WebExtAPIRef("tabs.sendMessage()")}}
+
Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The {{WebExtAPIRef('runtime.onMessage')}} event is fired in each content script running in the specified tab for the current extension.
+
{{WebExtAPIRef("tabs.getSelected()")}}
+
Gets the tab that is selected in the specified window.
+
{{WebExtAPIRef("tabs.getAllInWindow()")}}
+
Gets details about all tabs in the specified window.
+
{{WebExtAPIRef("tabs.create()")}}
+
Creates a new tab.
+
{{WebExtAPIRef("tabs.duplicate()")}}
+
Duplicates a tab.
+
{{WebExtAPIRef("tabs.query()")}}
+
Gets all tabs that have the specified properties, or all tabs if no properties are specified.
+
{{WebExtAPIRef("tabs.highlight()")}}
+
Highlights the given tabs.
+
{{WebExtAPIRef("tabs.update()")}}
+
Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified.
+
{{WebExtAPIRef("tabs.move()")}}
+
Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows.
+
{{WebExtAPIRef("tabs.reload()")}}
+
Reload a tab.
+
{{WebExtAPIRef("tabs.remove()")}}
+
Closes one or more tabs.
+
{{WebExtAPIRef("tabs.detectLanguage()")}}
+
Detects the primary language of the content in a tab.
+
{{WebExtAPIRef("tabs.captureVisibleTab()")}}
+
Captures the visible area of the currently active tab in the specified window. You must have <all_urls> permission to use this method.
+
{{WebExtAPIRef("tabs.executeScript()")}}
+
Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc.
+
{{WebExtAPIRef("tabs.insertCSS()")}}
+
Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc.
+
{{WebExtAPIRef("tabs.setZoom()")}}
+
Zooms a specified tab.
+
{{WebExtAPIRef("tabs.getZoom()")}}
+
Gets the current zoom factor of a specified tab.
+
{{WebExtAPIRef("tabs.setZoomSettings()")}}
+
Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab.
+
{{WebExtAPIRef("tabs.getZoomSettings()")}}
+
Gets the current zoom settings of a specified tab.
+
+ +

Events

+ +
+
{{WebExtAPIRef("tabs.onCreated")}}
+
Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.
+
{{WebExtAPIRef("tabs.onUpdated")}}
+
Fired when a tab is updated.
+
{{WebExtAPIRef("tabs.onMoved")}}
+
Fired when a tab is moved within a window. Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see {{WebExtAPIRef('tabs.onDetached')}}.
+
{{WebExtAPIRef("tabs.onSelectionChanged")}}
+
Fires when the selected tab in a window changes.
+
{{WebExtAPIRef("tabs.onActiveChanged")}}
+
Fires when the selected tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to {{WebExtAPIRef('tabs.onUpdated')}} events to be notified when a URL is set.
+
{{WebExtAPIRef("tabs.onActivated")}}
+
Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.
+
{{WebExtAPIRef("tabs.onHighlightChanged")}}
+
Fired when the highlighted or selected tabs in a window changes.
+
{{WebExtAPIRef("tabs.onHighlighted")}}
+
Fired when the highlighted or selected tabs in a window changes.
+
{{WebExtAPIRef("tabs.onDetached")}}
+
Fired when a tab is detached from a window, for example because it is being moved between windows.
+
{{WebExtAPIRef("tabs.onAttached")}}
+
Fired when a tab is attached to a window, for example because it was moved between windows.
+
{{WebExtAPIRef("tabs.onRemoved")}}
+
Fired when a tab is closed.
+
{{WebExtAPIRef("tabs.onReplaced")}}
+
Fired when a tab is replaced with another tab due to prerendering or instant.
+
{{WebExtAPIRef("tabs.onZoomChange")}}
+
Fired when a tab is zoomed.
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.tabs")}}

+ + + +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.tabs API. This documentation is derived from tabs.json in the Chromium code.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html b/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html new file mode 100644 index 0000000000..3f0da7eada --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/webrequest/index.html @@ -0,0 +1,188 @@ +--- +title: ВебЗапрос +slug: Mozilla/Add-ons/WebExtensions/API/webRequest +translation_of: Mozilla/Add-ons/WebExtensions/API/webRequest +--- +
{{AddonSidebar}}
+ +

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

+ +

Каждое событие запущено на определённой стадии запроса. Типичный порядок событий такой:

+ +

{{WebExtAPIRef("webRequest.onErrorOccurred", "onErrorOccurred")}} Может быть запущен в любой момент во время запроса. Чреда событий может отличаться от приведенной выше: например, в Firefox, после HSTS обновления, событие onBeforeRedirect будет запущено сразу же после onBeforeRequest.

+ +

Все события, кроме onErrorOccurred, могут принимать три аргумента в  addListener():

+ + + +

Функции - обработчику передается обьект details который содержит информацию о запросе. Она содержит ID запроса, который обеспечен для включения надстройки, которая позволяет соотносить события, ассоциируемые с одним запросом. Это уникально в пределах сессии и контекста надстройки. Информация остается одинаковой везде на протяжении запроса, даже при перенаправлениях и обменах аутентификации.

+ +

Для использования webRequest API для определённого хоста, расширение должно иметь "webRequest" API permission и host permission для этого хоста. Для использования возможности "блокирования" расширение должно также иметь "webRequestBlocking" API разрешение.

+ +

Для перехвата ресурсов, загруженных страницей (таких как картинки, скрипты или таблицы стилей), расширение должно иметь разрешение хоста для ресурса также как и для главной страницы, запрашивающей ресурс. К примеру, если страница на "https://developer.mozilla.org" загружает картинку из "https://mdn.mozillademos.org", тогда расширение должно иметь разрешения обоих хостов чтобы перехватить запрос картинки.

+ +

Модифицирование заголовков

+ +

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

+ + + +

Чтобы сделать это, вам необходимо передать оцпию со значением "blocking" в аргументе extraInfoSpec к  addListener(). Это делает обработчик синхронным. В обработчике, вы можете тогда возвратить обьект {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} который индикует модификацию, какую вам нужно сделать: например, модифицированный заголовок запроса который вы хотите отправить.

+ +

Доступ к информации о безопасности

+ +

В обработчике {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} вы имеете доступ к TLS свойствам запроса через вызов {{WebExtAPIRef("webRequest.getSecurityInfo()", "getSecurityInfo()")}}. Чтоды сделать это, вы должны также передать "blocking" в  extraInfoSpec аргументе к  addListener() события.

+ +

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

+ +

Modifying responses

+ +

Для того, чтобы модифицировать тело HTTP ответа на запрос, вызовите {{WebExtAPIRef("webRequest.filterResponseData")}}, и передайте ID запроса. Это возвратит обьект {{WebExtAPIRef("webRequest.StreamFilter")}} который вы сможете использовать чтобы исследовать и изменять данные когда они получены браузером.

+ +

Чтобы сделать это, у вас дожно быть "webRequestBlocking" API разрешение, а также "webRequest" API permission и host permission от соответствующего хоста.

+ +

Types

+ +
+
{{WebExtAPIRef("webRequest.BlockingResponse")}}
+
+

An object of this type is returned by event listeners that have set "blocking" in their extraInfoSpec argument. By setting particular properties in BlockingResponse, the listener can modify network requests.

+
+
{{WebExtAPIRef("webRequest.CertificateInfo")}}
+
An object describing a single X.509 certificate.
+
{{WebExtAPIRef("webRequest.HttpHeaders")}}
+
An array of HTTP headers. Each header is represented as an object with two properties: name and either value or binaryValue.
+
{{WebExtAPIRef("webRequest.RequestFilter")}}
+
An object describing filters to apply to webRequest events.
+
{{WebExtAPIRef("webRequest.ResourceType")}}
+
Represents a particular kind of resource fetched in a web request.
+
{{WebExtAPIRef("webRequest.SecurityInfo")}}
+
An object describing the security properties of a particular web request.
+
{{WebExtAPIRef("webRequest.StreamFilter")}}
+
An object that can be used to monitor and modify HTTP responses while they are being received.
+
{{WebExtAPIRef("webRequest.UploadData")}}
+
Contains data uploaded in a URL request.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES")}}
+
The maximum number of times that handlerBehaviorChanged() can be called in a 10 minute period.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("webRequest.handlerBehaviorChanged()")}}
+
This function can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache.
+
{{WebExtAPIRef("webRequest.filterResponseData()")}}
+
Returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object for a given request.
+
{{WebExtAPIRef("webRequest.getSecurityInfo()")}}
+
Gets detailed information about the TLS connection associated with a given request.
+
+ +

Events

+ +
+
{{WebExtAPIRef("webRequest.onBeforeRequest")}}
+
Fired when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.
+
{{WebExtAPIRef("webRequest.onBeforeSendHeaders")}}
+
Fired before sending any HTTP data, but after HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers.
+
{{WebExtAPIRef("webRequest.onSendHeaders")}}
+
Fired just before sending headers. If your add-on or some other add-on modified headers in {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}, you'll see the modified version here.
+
{{WebExtAPIRef("webRequest.onHeadersReceived")}}
+
Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers.
+
{{WebExtAPIRef("webRequest.onAuthRequired")}}
+
Fired when the server asks the client to provide authentication credentials. The listener can do nothing, cancel the request, or supply authentication credentials.
+
{{WebExtAPIRef("webRequest.onResponseStarted")}}
+
Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.
+
{{WebExtAPIRef("webRequest.onBeforeRedirect")}}
+
Fired when a server-initiated redirect is about to occur.
+
{{WebExtAPIRef("webRequest.onCompleted")}}
+
Fired when a request is completed.
+
{{WebExtAPIRef("webRequest.onErrorOccurred")}}
+
Fired when an error occurs.
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.webRequest")}}

+ +

Extra notes on Chrome incompatibilities.

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.webRequest API. This documentation is derived from web_request.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/windows/createtype/index.html b/files/ru/mozilla/add-ons/webextensions/api/windows/createtype/index.html new file mode 100644 index 0000000000..efc9821f8c --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/windows/createtype/index.html @@ -0,0 +1,65 @@ +--- +title: windows.CreateType +slug: Mozilla/Add-ons/WebExtensions/API/windows/CreateType +translation_of: Mozilla/Add-ons/WebExtensions/API/windows/CreateType +--- +
{{AddonSidebar()}}
+ +

Определение типа окна браузера для создания.

+ +

Тип

+ +

Значение данного типа strings. Возможные значения:

+ + + +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.api.windows.CreateType")}}

+ +

{{WebExtExamples}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.windows API. This documentation is derived from windows.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/api/windows/index.html b/files/ru/mozilla/add-ons/webextensions/api/windows/index.html new file mode 100644 index 0000000000..889210561b --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/api/windows/index.html @@ -0,0 +1,106 @@ +--- +title: windows +slug: Mozilla/Add-ons/WebExtensions/API/windows +translation_of: Mozilla/Add-ons/WebExtensions/API/windows +--- +
{{AddonSidebar}}
+ +

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

+ +

Types

+ +
+
{{WebExtAPIRef("windows.WindowType")}}
+
Тип окна браузера.
+
{{WebExtAPIRef("windows.WindowState")}}
+
Состояние окна браузера.
+
{{WebExtAPIRef("windows.Window")}}
+
Информация об окне браузера.
+
{{WebExtAPIRef("windows.CreateType")}}
+
Specifies the type of browser window to create.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("windows.WINDOW_ID_NONE")}}
+
The windowId value that represents the absence of a browser window.
+
{{WebExtAPIRef("windows.WINDOW_ID_CURRENT")}}
+
The windowId value that represents the current window.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("windows.get()")}}
+
Gets details about a window, given its ID.
+
{{WebExtAPIRef("windows.getCurrent()")}}
+
Gets the current window.
+
{{WebExtAPIRef("windows.getLastFocused()")}}
+
Gets the window that was most recently focused — typically the window 'on top'.
+
{{WebExtAPIRef("windows.getAll()")}}
+
Gets all windows.
+
{{WebExtAPIRef("windows.create()")}}
+
+

Creates a new window.

+
+
{{WebExtAPIRef("windows.update()")}}
+
Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.
+
{{WebExtAPIRef("windows.remove()")}}
+
Closes a window, and all its tabs.
+
+ +

Events

+ +
+
{{WebExtAPIRef("windows.onCreated")}}
+
Fired when a window is created.
+
{{WebExtAPIRef("windows.onRemoved")}}
+
Fired when a window is closed.
+
{{WebExtAPIRef("windows.onFocusChanged")}}
+
Fired when the currently focused window changes.
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.windows")}}

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.windows API. This documentation is derived from windows.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/ru/mozilla/add-ons/webextensions/chrome_incompatibilities/index.html b/files/ru/mozilla/add-ons/webextensions/chrome_incompatibilities/index.html new file mode 100644 index 0000000000..70e5f2e7e1 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/chrome_incompatibilities/index.html @@ -0,0 +1,331 @@ +--- +title: Chrome incompatibilities +slug: Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities +translation_of: Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities +--- +
{{AddonSidebar}}
+ +

Веб расширения разработаны с поддержкой совместимости с расширениями Хрома и Оперы на сколько это возможно. Расширения, написанные для этих браузеров, должны работать в Firefox с минимальными изменениями.

+ +

Все же, Firefox на данный момент имеет поддержку только для ограниченного набора функций и API, поддержуемых в Хроме и Опере. Мы работаем над добавлением большей поддержки, но много функций пока еще не поддерживаются и некоторые из них никогда не будут поддерживаться.

+ +

Эта статья перечисляет все функции и API, которые полностью поддерживаются в Firefox Developer Edition (на данный момент Firefox 47). Там где функция поддерживается частично, мы указали на проблемные места.

+ +
+

You should assume that features and APIs not listed here at all are not yet supported.

+
+ +

manifest.json функция

+ +

Полностью поддерживаемые ключи:

+ + + +

Частично поддерживаемые ключи:

+ +

background

+ +

Firefox не поддерживает "устойчивое" свойство. Фоновые скрипты остаются загруженными всё время.

+ +

commands

+ +

Firefox не поддерживает:

+ + + +

content_scripts

+ +

Firefox не поддерживает:

+ + + +

content_security_policy

+ +

Firefox не поддерживает:

+ + + +

options_ui

+ +

Firefox не поддерживает:

+ + + +

Using options_ui requires a valid value for the applications.gecko.id property.

+ +

permissions

+ +

Firefox не поддерживает следующие разрешения:

+ + + +

Obviously, it doesn't support permissions for APIs that are themselves not supported.

+ +

incognito

+ +

Firefox does not support the following incognito (private browsing) modes:

+ + + +

JavaScript APIs

+ +

Fully supported APIs

+ + + +

Partially supported APIs

+ +

bookmarks

+ + + +

contextMenus

+ + + +

downloads

+ + + +

extension

+ + + +

idle

+ + + +

Additoinally, queryState() always returns "active" in Firefox, regardless of the current system idle state.

+ +

notifications

+ + + +

runtime

+ + + +

storage

+ + + +

tabs

+ + + +

webNavigation

+ + + +

webRequest

+ + + +

windows

+ + + +

Planned APIs

+ +

We don't support the following APIs, but plan to, soon:

+ + + +

This doesn't mean that these are the only additional APIs we will support, but that they are our current priorities.

+ +

Miscellaneous incompatibilities

+ +

Optional arguments

+ +

URLs in CSS

+ +

Firefox resolves URLs in injected CSS files relative to the CSS file itself, rather than to the page it's injected into.

+ +

Additional incompatibilities

+ +

Firefox does not support using alert() from background pages. Using alert(message) from a background page will cause the Browser Console to be opened and both a line stating "alert() is not supported in background windows; please use console.log instead." and the message will be output to the console.

diff --git a/files/ru/mozilla/add-ons/webextensions/content_scripts/index.html b/files/ru/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..2451aabce6 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,495 @@ +--- +title: Встраиваемый скрипт +slug: Mozilla/Add-ons/WebExtensions/Content_scripts +tags: + - Web-расширение + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +
{{AddonSidebar}}
+ +

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

+ +

Фоновые скрипты имеют доступ ко всем методам WebExtension JavaScript APIs, но они не имеют доступа к контенту отдельных веб-страниц. Так что если вашему расширению необходимо взаимодействие с контентом веб-страницы, вам нужен встраиваемый скрипт.

+ +

Точно так же, как скрипты загружаемые веб-страницами, встраиваемый скрипт может читать и изменять контент веб-страницы, используя DOM API.

+ +

Встраиваемые скрипты имеют доступ только к небольшому подмножеству методов WebExtension API, но они могут взаимодействовать с фоновыми скриптами, используя систему передачи сообщений, таким образом опосредовано имея доступ ко всему WebExtension API.

+ +
+

Обратите внимание, что встраивание скриптов блокируется на следующих доменах:

+ + + +

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

+ +

По причине того, что список запрещённых доменов включает в себя addons.mozilla.org, пользователи, которые попытаются испытать ваше расширение прямо на странице загрузки, могут посчитать, что расширение не работает! В связи с этим вы могли бы предоставить им соответствующее предупреждение или onboarding page чтобы немедленно переадресовать их с addons.mozilla.org.

+
+ +
+

Значения, определённые в глобальной области видимости встраиваемого скрипта с помощью var foo или window.foo = "bar" могут исчезать по причине бага 1408996.

+
+ +

Загрузка встраиваемого скрипта

+ +

Загрузка встраиваемых скриптов на веб-страницу происходит следующими тремя способами:

+ +
    +
  1. Автоматическая загрузка скрипта на страницах с определёнными URL, объявленными при установке: используя content_scripts ключ в manifest.json, вы можете запросить браузер загружать встраиваемый скрипт каждый раз, когда браузер загружает веб-страницу, чей URL совпадает с объявленными шаблонами.
  2. +
  3. Автоматическая загрузка скрипта на страницах с определёнными URL, объявленными в момент работы расширения: используя {{WebExtAPIRef("contentScripts")}} API, вы можете запросить браузер загружать встраиваемый скрипт каждый раз, когда браузер загружает веб-страницу, чей URL совпадает с объявленными шаблонами. Это очень похоже на первый метод, но позволяет добавлять и удалять правила динамически во время работы расширения.
  4. +
  5. Загрузка скрипта расширением в конкретную вкладку: используя tabs.executeScript() API, вы можете загружать встраиваемые скрипты в определённые вкладки когда захотите: например, в ответ на нажатие пользователя на browser action.
  6. +
+ +

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

+ +

Используя методы (1) и (2), вы можете загружать скрипты на страницы, чьи URL могут быть представлены, используя шаблон совпадения.

+ +

Используя метод (3), вы к тому же можете загружать скрипты на страницы вашего расширения, но вы не можете загружать скрипты на привилегированные страницы браузеры (например "about:debugging" или "about:addons").

+ +

Условия работы встраиваемого скрипта

+ +

Доступ к DOM

+ +

Встраиваемые скрипты имеют доступ и могут изменять DOM на веб-странице, так же как и обычные скрипты. Так же они могут видеть любые изменения сделанные с DOM страничными скриптами.

+ +

При этом, встраиваемые скрипты имеют "чистое DOM представление". Это значит:

+ + + +

В Firefox это поведение называется Xray vision.

+ +

Например, рассмотрите эту веб-страницу:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+  </head>
+
+  <body>
+    <script src="page-scripts/page-script.js"></script>
+  </body>
+</html>
+ +

Скрипт "page-script.js" делает следующее:

+ +
// page-script.js
+
+// добавляет новый элемент к DOM
+var p = document.createElement("p");
+p.textContent = "Этот параграф был добавлен страничным скриптом.";
+p.setAttribute("id", "page-script-para");
+document.body.appendChild(p);
+
+// определяет новое свойство на объекте window
+window.foo = "Эта глобальная переменная была добавлена страничным скриптом";
+
+// переопределяет встроенную window.confirm() функцию
+window.confirm = function() {
+  alert("Страничный скрипт так же переопределил 'confirm'");
+}
+ +

Теперь расширение загружает встраиваемый скрипт на страницу:

+ +
// content-script.js
+
+// получает доступ и изменяет DOM
+var pageScriptPara = document.getElementById("page-script-para");
+pageScriptPara.style.backgroundColor = "blue";
+
+// не может видеть свойств определённых страничным скриптом
+console.log(window.foo);  // undefined
+
+// видит изначальное значение свойства, переопределённого страничным скриптом
+window.confirm("Вы уверены?"); // вызывает оригинальный window.confirm()
+ +

Те же самые правила применяются и наоборот: страничный скрипт не может видеть JavaScript свойств, добавленных встраиваемым скриптом.

+ +

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

+ +

Одно из последствий такого поведения состоит в том, что встраиваемый скрипт не будет иметь доступ к JavaScript библиотекам, загруженным страничным скриптом. Например, если веб-страница загружает jQuery, встраиваемый скрипт не сможет увидеть эту библиотеку.

+ +

Если встраиваемому скрипту необходимо использовать какую-либо JavaScript библиотеку, тогда эта библиотека должна быть загружена, тем же способом, как и встраиваемый скрипт вместе с ним:

+ +
"content_scripts": [
+  {
+    "matches": ["*://*.mozilla.org/*"],
+    "js": ["jquery.js", "content-script.js"]
+  }
+]
+ +
+

Примечание: Firefox предоставляет некоторое API, позволяющее встраиваемому скрипту иметь доступ к JavaScript объектам, созданным страничным скриптом, и предоставлять свои собственные JavaScript объекты страничному скрипту.

+ +

Смотрите совместное использование объектов со страничным скриптом для получения дополнительной информации.

+
+ +

Доступные WebExtension API

+ +

В дополнение стандартному DOM API, встраиваемый скрипт может использовать следующие методы WebExtension APIs:

+ +

Из extension:

+ + + +

Из runtime:

+ + + +

Из i18n:

+ + + +

Из menus:

+ + + +

Ко всему из storage.

+ +

Работа с XHR и Fetch

+ +

Встраиваемые скрипты могут делать запросы используя window.XMLHttpRequest и window.fetch() API.

+ +
+

В Firefox, запросы, совершаемые из встраиваемого скрипта (например, используя fetch()) происходят в контексте расширения, так что вам необходимо предоставлять полный URL для доступа к контенту страниц. В Chrome, эти запросы совершаются в контексте страницы, так что URL может быть относительным, например /api будет трансформирован в https://[current page URL]/api.

+
+ +

Встраиваемый скрипт имеет точно такие же кросс-доменные привилегии, как и всё остальное расширение: так что если расширение запросило кросс-доменный доступ на какой-либо домен используя permissions ключ в manifest.json, тогда его встраиваемый скрипт тоже будет иметь доступ к этому домену.

+ +

Это достигается, предоставляя встраиваемому скрипту более привилегированные XHR and fetch объекты. Что имеет побочный эффект, связанный с отсутствием Origin и Referer заголовков, которые имел бы запрос, выполняемый из страничного скрипта. Зачастую это предпочитаемо, для того чтобы предотвратить раскрытие кросс-доменной натуры запроса. Начиная с версии 58 и дальше, расширения, которым необходимо выполнять запросы, которые должны выглядеть будто они отправлены встраиваемым скриптом, могут использовать  content.XMLHttpRequest и content.fetch(). Кросс-браузерные расширения должны проверять присутствие этих методов.

+ +

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

+ +

Хотя встраиваемые скрипты не могут напрямую использовать большинство методов из WebExtension APIs, они могут взаимодействовать с фоновыми скриптами расширения, используя систему сообщений, и таким образом могут опосредованно иметь доступ к тем же самым API, что и фоновые скрипты.

+ +

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

+ +

Одиночные сообщения

+ +

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

+ + + + + + + + + + + + + + + + + + + + + +
Во встраиваемом скриптеВ фоновом скрипте
Отправка сообщенияbrowser.runtime.sendMessage()browser.tabs.sendMessage()
Получение сообщенияbrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

Например, представьте встраиваемый скрипт, который прослушивает веб-страницу на нажатие левой кнопки мыши.

+ +

Если нажатие было произведено по ссылке, встраиваемый скрипт отправляет сообщение фоновому скрипту со значение URL в ссылке:

+ +
// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+  if (e.target.tagName != "A") {
+    return;
+  }
+  browser.runtime.sendMessage({"url": e.target.href});
+}
+ +

Фоновый скрипт ожидает эти сообщения и, при их получении, отображает уведомления, используя notifications API:

+ +
// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+  browser.notifications.create({
+    "type": "basic",
+    "iconUrl": browser.extension.getURL("link.png"),
+    "title": "Вы нажали на ссылку!",
+    "message": message.url
+  });
+}
+
+ +

(Этот пример кода частично взят из notify-link-clicks-i18n примера на GitHub.)

+ +

Обмен сообщениями через постоянное соединение

+ +

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

+ +

Каждая из сторон имеет runtime.Port объект, который они могут использовать для обмена сообщениями.

+ +

Для создания постоянного соединения:

+ + + +

Результатом вызова этих методов будет возвращение runtime.Port объекта.

+ + + +

Как только обе стороны имеют порт, они могут:

+ + + +

Например, сразу после загрузки, нижерасположенный встраиваемый скрипт:

+ + + +
// content-script.js
+
+var myPort = browser.runtime.connect({name:"port-from-cs"});
+myPort.postMessage({greeting: "Привет из встраиваемого скрипта"});
+
+myPort.onMessage.addListener(function(m) {
+  console.log("Во встраиваемом скрипте, получено сообщение из фонового скрипта: ");
+  console.log(m.greeting);
+});
+
+document.body.addEventListener("click", function() {
+  myPort.postMessage({greeting: "Они кликнули по странице!"});
+});
+ +

Соответствующий фоновый скрипт:

+ + + +
// background-script.js
+
+var portFromCS;
+
+function connected(p) {
+  portFromCS = p;
+  portFromCS.postMessage({greeting: "Привет, встраиваемый скрипт!"});
+  portFromCS.onMessage.addListener(function(m) {
+    console.log("В фоновом скрипте, получено сообщение от встраиваемого скрипта");
+    console.log(m.greeting);
+  });
+}
+
+browser.runtime.onConnect.addListener(connected);
+
+browser.browserAction.onClicked.addListener(function() {
+  portFromCS.postMessage({greeting: "Они нажали кнопку!"});
+});
+
+ +

Несколько встраиваемых скриптов

+ +

Если вы имеете несколько встраиваемых скриптов, с которыми вы общающаетесь в одно и то же время, вы бы могли сохранять каждое соединение в массиве.

+ + + +
// background-script.js
+
+var ports = []
+
+function connected(p) {
+  ports[p.sender.tab.id]    = p
+  //...
+}
+
+browser.runtime.onConnect.addListener(connected)
+
+browser.browserAction.onClicked.addListener(function() {
+  ports.forEach(p => {
+        p.postMessage({greeting: "Они нажали на кнопку!"})
+    })
+});
+
+ + + +

Взаимодействие с веб-страницей

+ +

Хотя по умолчанию встраиваемые скрипты не имеют доступ к объектам, которые созданны страничными скриптами, они могут взаимодействовать со страничными скриптами, используя window.postMessage и window.addEventListener API.

+ +

Например:

+ +
// page-script.js
+
+var messenger = document.getElementById("from-page-script");
+
+messenger.addEventListener("click", messageContentScript);
+
+function messageContentScript() {
+  window.postMessage({
+    direction: "from-page-script",
+    message: "Сообщение со страницы"
+  }, "*");
+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data &&
+      event.data.direction == "from-page-script") {
+    alert("Встраиваемый скрипт получил сообщение: \"" + event.data.message + "\"");
+  }
+});
+ +

Для просмотра законченного и полностью рабочего примера, посетите эту страницу на GitHub и следуйте инструкциям.

+ +
+

Заметьте, при взаимодействии с непроверенными страницами этим способом, вам нужно быть очень осторожными . Расширения имеют возможность запускать привилегированный код, который может обладать серьёзными возможностями, и вредоносные веб-страницы легко могут обмануть ваше расширение, ради доступа к этим возможностям.

+ +

Как простейший пример, представим встраиваемый скрипт, который получает сообщение от веб-страницы и делает что-то вроде этого:

+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data.direction &&
+      event.data.direction == "from-page-script") {
+    eval(event.data.message);
+  }
+});
+ +

Теперь страничный скрипт может запускать любой код со всеми привилегиями встраиваемого скрипта.

+
+ +

Использование eval() во встраиваемых скриптах

+ +

В Chrome, eval() всегда выполняет код в контексте встраиваемого скрипта, а не в контексте веб-страницы.

+ +

В Firefox:

+ + + +

Например, рассмотрите этот встраиваемый скрипт:

+ +
// content-script.js
+
+window.eval('window.x = 1;');
+eval('window.y = 2');
+
+console.log(`Во встраиваемом скрипте, window.x: ${window.x}`);
+console.log(`Во встраиваемом скрипте, window.y: ${window.y}`);
+
+window.postMessage({
+  message: "check"
+}, "*");
+ +

Этот код создаёт переменные x and y, используя window.eval() и eval(), затем записывает их значения, и отправляет сообщение на веб-страницу.

+ +

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

+ +
window.addEventListener("message", function(event) {
+  if (event.source === window && event.data && event.data.message === "check") {
+    console.log(`In page script, window.x: ${window.x}`);
+    console.log(`In page script, window.y: ${window.y}`);
+  }
+});
+ +

В Chrome, в консоли будут записаны следующие строки:

+ +
In content script, window.x: 1
+In content script, window.y: 2
+In page script, window.x: undefined
+In page script, window.y: undefined
+ +

В Firefox, будут записаны следующие строки:

+ +
In content script, window.x: undefined
+In content script, window.y: 2
+In page script, window.x: 1
+In page script, window.y: undefined
+ +

Те же правила применимы к setTimeout(), setInterval(), и Function().

+ +
+

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

+ +
// page.js переопределяет console.log
+
+var original = console.log;
+
+console.log = function() {
+  original(true);
+}
+
+ + +
// content-script.js вызывает переопределённую версию
+
+window.eval('console.log(false)');
+
+
diff --git a/files/ru/mozilla/add-ons/webextensions/content_security_policy/index.html b/files/ru/mozilla/add-ons/webextensions/content_security_policy/index.html new file mode 100644 index 0000000000..2a620b3a39 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/content_security_policy/index.html @@ -0,0 +1,111 @@ +--- +title: Политика защиты содержимого +slug: Mozilla/Add-ons/WebExtensions/Content_Security_Policy +tags: + - Web-расширение + - Безопасность + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/Content_Security_Policy +--- +
{{AddonSidebar}}
+ +
+

Политика защиты содержимого (англ. Content Security Policy) автоматически применяется ко всем расширениям, разработанным с использованием WebExtension API. Она ограничивает источники, из которых расширение может загружать <script> и <object> ресурсы, и препятствует потенциально опасным практикам, например использованию eval().

+ +

Статья в краткой форме объясняет значимость этой политики, каковы её изначальные правила, как они влияют на расширение, и как расширение может изменять эти правила.

+
+ +

Политика защиты содержимого - это механизм, помогающий веб-сайтам предотвращать выполнение умышленно вредного кода. Веб-сайт устанавливает политику защиты, используя HTTP заголовок, посылаемый с сервера. Главным образом эта политика участвует в устанавливании допустимых источников для загрузки различного вида контента, к примеру, скриптов или встроенных плагинов. Например, веб-сайт может использовать политику защиты для инструктирования браузера, чтобы тот выполнял скрипты, загруженные только с самого сайта, а не из каких-либо других источников. Политика защиты содержимого так же может запретить браузеру использовать потенциально опасные практики, например использование eval().

+ +

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

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+  </head>
+
+  <body>
+
+    <!-- Некоторый HTML контент -->
+
+    <!--
+      Подключение сторонней библиотеки.
+      Смотрите так же https://developer.mozilla.org/ru/docs/Web/Security/Subresource_Integrity.
+    -->
+    <script>
+      src="https://code.jquery.com/jquery-2.2.4.js"
+      integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
+      crossorigin="anonymous">
+    </script>
+
+    <!-- Include my popup's own script-->
+    <script src="popup.js"></script>
+  </body>
+
+</html>
+ +

В сравнении с веб-сайтами, расширения имеют доступ к дополнительному привилегированному API, так что вероятность получения к нему доступа сторонним кодом - это очень большой риск. По этой причине:

+ + + +

Изначальные правила по защите содержимого

+ +

Следующие правила по защите содержимого являются изначальными:

+ +
"script-src 'self'; object-src 'self';"
+ +

Они применяются к любому расширению, которое самостоятельно не указывает свою политику защиты, используя content_security_policy ключ в manifest.json. Это имеет следующие последствия:

+ + + +

Расположение script и object ресурсов

+ +

Используя изначальную политику защиты содержимого, вы можете загружать только локальные к расширению <script> и <object> ресурсы. Например, рассмотрите эту строку из документа расширения:

+ +
 <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
+ +

Она не будет загружать запрашиваемый ресурс, и вы не сможете найти ни один ожидаемый от ресурса объект. К этой ситуации существует два решения:

+ + + +

eval() и товарищи

+ +

Изначальная политика защиты содержимого не позволяет выполнять код из JavaScript строк. Это означает, что следующие примеры кода изначально запрещены:

+ +
eval("console.log('some output');");
+ +
window.setTimeout("alert('Hello World!');", 500);
+ +
var f = new Function("console.log('foo');");
+ +

Встраиваемый (inline) JavaScript

+ +

Изначальная политика защиты содержимого не позволяет выполнять JavaScript код, встраиваемый в HTML теги. Это запрещает как выполнение JavaScript кода вложенного прямо в <script> тег, так и выполнение вписанных в атрибут обработчиков событий, означая, что следующий код так же не будет работать:

+ +
<script>console.log("foo");</script>
+ +
<div onclick="console.log('click')">Click me!</div>
+ +

Вместо того, чтобы использовать код <body onload="main()"> для запуска вашего скрипта после загрузки страницы, поставьте обработчики событий на DOMContentLoaded или load.

diff --git a/files/ru/mozilla/add-ons/webextensions/examples/index.html b/files/ru/mozilla/add-ons/webextensions/examples/index.html new file mode 100644 index 0000000000..e59d8c1f7f --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/examples/index.html @@ -0,0 +1,34 @@ +--- +title: Примеры расширений +slug: Mozilla/Add-ons/WebExtensions/Examples +tags: + - WebExtensions + - Веб-расширения + - Интерфейс +translation_of: Mozilla/Add-ons/WebExtensions/Examples +--- +
{{AddonSidebar}}
+ +

В целях иллюстрации разработки расширений, мы поддерживаем репозиторий простых демонстрационных расширений по адресу https://github.com/mdn/webextensions-examples. Данная статья описывает, как использовать эти примеры, и перечисляет их вместе с API Веб-расширений (WebExtensions API), которые они демонстрируют.

+ +

Эти примеры работают в Firefox Nightly: большинство из них работает и в более ранних версиях Firefox, но, чтобы удостовериться, проверьте поле strict_min_version в файле manifest.json.

+ +
+

Некоторые примеры работают только на специальных доменах или страницах. Подробности о всех ограничениях представлены в файле readme каждого примера. По умолчанию ни один из примеров не работает в приватных окнах браузера, подробности смотрите в Extensions in Private Browsing.

+
+ +

Если Вы хотите попробовать эти примеры, клонируйте репозиторий, а после этого совершите одно из следующих действий:

+ +
    +
  1. Загрузите расширение из папки с его исходниками, используя функцию браузера Load Temporary Add-on. Расширение останется загруженным до следующего перезапуска Firefox.
  2. +
  3. Откройте папку с исходниками расширения в командной строке и используйте команду web-ext, чтобы запустить расширение. Расширение останется загруженным до следующего перезапуска Firefox.
  4. +
  5. В браузере Firefox используйте Файл > Открыть файл и найдите расширение в папке build. Папка build содержит построенные и подписанные версии всех примеров. В результате пример установится надолго, как обычное расширение.
  6. +
+ +
+

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

+
+ +

Если Вы хотите сделать свой вклад в репозиторий, отправьте нам pull request!

+ +

{{WebExtAllExamples}}

diff --git a/files/ru/mozilla/add-ons/webextensions/index.html b/files/ru/mozilla/add-ons/webextensions/index.html new file mode 100644 index 0000000000..c25919686b --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/index.html @@ -0,0 +1,109 @@ +--- +title: Расширения браузера +slug: Mozilla/Add-ons/WebExtensions +tags: + - Landing + - WebExtensions + - Дополнения + - Расширения +translation_of: Mozilla/Add-ons/WebExtensions +--- +
{{AddonSidebar}}
+ +

WebExtensions - это кросс-браузерная система разработки дополнений (для браузеров). В значительной степени эта система совместима с API-расширений, поддерживаемых Google Chrome и Opera. Расширения, написанные для этих браузеров, в большинстве случаев будут работать с Firefox или Microsoft Edge лишь с минимальными изменениями. Эти API также полностью совместимы с мультипоточным Firefox.

+ +

Также мы намерены расширять API для поддержки нужд разработчиков дополнений, поэтому, если у вас есть идеи, то мы их с удовольствием выслушаем. Вы можете связаться с нами через dev-addons mailing list или #webextensions на IRC.

+ +
+
+

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

+ + + +

How to

+ + + +

Интерфейс пользователя

+ + + +

Основные понятия

+ + + +

Адаптация

+ + + +

Рабочий процесс (workflow) Firefox

+ + +
+ +
+

Справочники

+ + + +

JavaScript APIs

+ +
{{ ListSubpages ("/ru/Add-ons/WebExtensions/API") }}
+ +

Manifest keys

+ +
{{ ListSubpages ("/ru/Add-ons/WebExtensions/manifest.json") }}
+
+
diff --git a/files/ru/mozilla/add-ons/webextensions/intercept_http_requests/index.html b/files/ru/mozilla/add-ons/webextensions/intercept_http_requests/index.html new file mode 100644 index 0000000000..91941e4595 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/intercept_http_requests/index.html @@ -0,0 +1,155 @@ +--- +title: Intercept HTTP requests +slug: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests +translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests +--- +
{{AddonSidebar}}
+ + + +

В этой статье мы рассмотрим три разных способа использования webRequest модуля:

+ + + +

Логирование URL запросов

+ +

Создайте новый каталог "requests". В нём создайте файл "manifest.json" со следующим содержимым:

+ +
{
+  "description": "Demonstrating webRequests",
+  "manifest_version": 2,
+  "name": "webRequest-demo",
+  "version": "1.0",
+
+  "permissions": [
+    "webRequest",
+    "<all_urls>"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+}
+ +

Далее, создайте файл "background.js" со следующим содержимым:

+ +
function logURL(requestDetails) {
+  console.log("Loading: " + requestDetails.url);
+}
+
+browser.webRequest.onBeforeRequest.addListener(
+  logURL,
+  {urls: ["<all_urls>"]}
+);
+
+
+ +

Здесь мы используем {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} для вызова функции logURL() перед началом запроса. Функция logURL() берёт URL запроса из объекта event и выводит в консоль браузера. Шаблон {urls: ["<all_urls>"]} означает, что мы будем перехватывать HTTP запросы ко всем URL.

+ +

Для проверки проинсталлируйте WebExtension, откройте консоль браузера и откройте какую-нибудь веб-страницу. В консоли вы должны увидеть URL для каждого ресурса, который запрашивает браузер:

+ +

{{EmbedYouTube("X3rMgkRkB1Q")}}

+ +

Перенаправление запросов

+ +

Теперь давайте использовать webRequest для перенаправления HTTP-запросов. Во-первых, замените manifest.json на это:

+ +
{
+
+  "description": "Demonstrating webRequests",
+  "manifest_version": 2,
+  "name": "webRequest-demo",
+  "version": "1.0",
+
+  "permissions": [
+    "webRequest",
+    "webRequestBlocking",
+    "https://mdn.mozillademos.org"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+
+}
+ +

Единственное изменение здесь заключается в добавлении "webRequestBlocking" в permission. Мы должны запрашивать это дополнительное разрешение каждый раз, когда мы изменяем запрос.

+ +

Затем замените «background.js» следующим образом:

+ +
var pattern = "https://mdn.mozillademos.org/*";
+
+function redirect(requestDetails) {
+  console.log("Redirecting: " + requestDetails.url);
+  return {
+    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
+  };
+}
+
+browser.webRequest.onBeforeRequest.addListener(
+  redirect,
+  {urls:[pattern], types:["image"]},
+  ["blocking"]
+);
+ +

Опять же, мы используем {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} прослушиватель событий для запуска функции непосредственно перед каждым запросом. Эта функция заменит целевой URL на redirectUrl указанный в функции.

+ +

На этот раз мы не перехватываем каждый запрос: опция {urls: [pattern], types: ["image"]} указывает, что мы должны перехватывать запросы (1) для URL-адресов, находящихся в разделе «https://mdn.mozillademos.org / "(2) для ресурсов изображения. Подробнее см. {{WebExtAPIRef ("webRequest.RequestFilter")}}.

+ +

Также обратите внимание, что мы передаем опцию "blocking": нам нужно передать это, когда мы хотим изменить запрос. Это заставляет функцию прослушивателя блокировать сетевой запрос, поэтому браузер ждет, пока слушатель вернется, прежде чем продолжить. Дополнительную информацию о "blocking" смотрите в документации {{WebExtAPIRef ("webRequest.onBeforeRequest")}}.

+ +

Чтобы проверить это, откройте страницу в MDN, которая содержит много изображений (например, https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), перезагрузите WebExtension и перезагрузите страницу MDN :

+ +

{{EmbedYouTube("ix5RrXGr0wA")}}

+ +

Modifying request headers

+ +

Finally we'll use webRequest to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".

+ +

The "manifest.json" can stay the same as in the previous example.

+ +

Replace "background.js" with code like this:

+ +
var targetPage = "http://useragentstring.com/*";
+
+var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
+
+function rewriteUserAgentHeader(e) {
+  for (var header of e.requestHeaders) {
+    if (header.name.toLowerCase() == "user-agent") {
+      header.value = ua;
+    }
+  }
+  return {requestHeaders: e.requestHeaders};
+}
+
+browser.webRequest.onBeforeSendHeaders.addListener(
+  rewriteUserAgentHeader,
+  {urls: [targetPage]},
+  ["blocking", "requestHeaders"]
+);
+ +

Here we use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent.

+ +

The listener function will be called only for requests to URLs matching the targetPage pattern. Also note that we've again passed "blocking" as an option. We've also passed "requestHeaders", which means that the listener will be passed an array containing the request headers that we expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options.

+ +

The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua variable, and returns the modified array. This modified array will now be sent to the server.

+ +

To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the add-on, reload useragentstring.com, and check that Firefox is now identified as Opera:

+ +

{{EmbedYouTube("SrSNS1-FIx0")}}

+ +

Learn more

+ +

To learn about all the things you can do with the webRequest API, see its reference documentation.

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/background/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/background/index.html new file mode 100644 index 0000000000..876f151d60 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/background/index.html @@ -0,0 +1,115 @@ +--- +title: ключ background +slug: Mozilla/Add-ons/WebExtensions/manifest.json/background +tags: + - WebExtensions + - Веб-расширения + - Дополнения + - Манифест + - Расширения +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/background +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
ТипObject
ОбязательныйНет
Пример +
+"background": {
+  "scripts": ["background.js"]
+}
+
+ +

Используйте ключ background для включения одного или нескольких фоновых сценариев и, возможно, фоновой страницы в ваше расширение.

+ +

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

+ +

Фоновые сценарии загружаются сразу при загрузке расширения и остаются загруженными до тех пор, пока расширение не будет отключено или удалено. Вы можете использовать любой API-интерфейс WebExtension в сценарии, если вы запросили необходимые права (permissions).

+ +

Дополнительную информацию см. В разделе «Справочные страницы» в статье Анатомия расширения.

+ +

Ключ background это объект, у которого есть два следующих необязательных свойства:

+ + + + + + + + + + + + +
scripts +

Массив строк, каждая из которых представляет собой путь к файлу JavaScript. Путь к этим файлам указывают относительно папки, в которой находится файл manifest.json. Это скрипты, которые будут выполняться в фоновой странице расширения.

+ +

У этих скриптов общий глобальный контекст объекта window.

+ +

Скрипты загружаются в том порядке, в котором они указаны в массиве.

+ +

Если вы указали значения с помощью свойства scripts, будет создана пустая фоновая страница, в которой будут работать все эти скрипты.

+ +
+

Примечание: Если вы хотите добавить скрипт из удалённого расположения с помощью тега <script> (например, <script src = "https://code.jquery.com/jquery-1.7.1.min.js">), может также понадобиться изменить значение ключа content_security_policy в файле manifest.json вашего расширения.

+
+ +
+

Примечание: В Firefox до версии 50, когда открыт отладчик, скрипты не всегда загружаются в том порядке, в котором они расположены в массиве. Чтобы обойти этот баг, можно использовать свойство page  (вместо scripts) и добавить фоновые скрипты с помощью тегов <script> в странице HTML. Этот баг починен в Firefox 50. Начиная с этой версии, скрипты всегда загружаются в том порядке, в котором они следуют в массиве.

+
+
page +

Если вам нужно какое-нибудь содержимое HTML-страницы, можно определить свою фоновую страницу с помощью свойства page. Это строка, которая представляет собой путь к файлу документа HTML, заданный относительно расположения файла manifest.json. Этот файл HTML должен находиться внутри вашего расширения.

+ +

Если используется это свойство, то уже нельзя добавлять скрипты с помощью свойства scripts. Вместо этого нужно добавлять скрипты в страницу — точно таким же образом, как в обычную веб-страницу.

+
+ +

Ключ background также может содержать следующее необязательное свойство:

+ + + + + + + + +
persistent +

Двоичное значение (Boolean).

+ +
    +
  • true определяет, что фоновая страница должна храниться в памяти с момента, когда загрузилось расширение или запустился браузер и до того, как расширение будет удалено или выключено, или браузер будет закрыт (то есть фоновая страница постоянна).
  • +
  • false определяет, что фоновая страница может быть выгружена из памяти во время бездействия и создана заново, когда будет нужна. Такие фоновые страницы часто называются «Страницами Событий» (Event Pages) — потому, что они загружаются в память только для того, чтобы обрабатывать события, для которых в фоновых скриптах назначены функции-обработчики. Зарегистрированные события остаются когда фоновая страница выгружена из памяти, но остальные значения сбрасываются. Если нужно хранить постоянные данные при использовании страницы событий, используйте storage API.
  • +
+
+ +

Примеры

+ +
  "background": {
+    "scripts": ["jquery.js", "my-background.js"]
+  }
+ +

Загрузит два фоновых скрипта.

+ +
  "background": {
+    "page": "my-background.html"
+  }
+ +

Загрузит файл фоновой страницы.

+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.background", 10)}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/content_security_policy/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/content_security_policy/index.html new file mode 100644 index 0000000000..0efe1fe0d5 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/content_security_policy/index.html @@ -0,0 +1,117 @@ +--- +title: content_security_policy +slug: Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy +tags: + - Web-расширение + - Безопасность + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
ТипСтрока
ОбязателенНет
Пример +
+"content_security_policy": "default-src 'self'"
+
+ +

Политика защиты содержимого применяется к расширениям автоматически. Изначальная политика защиты содержимого ограничивает источники, из которых расширение может загружать <script> и <object> ресурсы, а так же препятствует потенциально опасным практикам, например использованию eval(). Смотрите изначальные правила защиты содержимого, чтобы узнать о конкретных последствиях применения изначальных правил.

+ +

Ключ "content_security_policy" в manifest.json используется для ослабления или ужесточения политики защиты содержимого. Значения для этого ключа устанавливаются в точно таком же виде, как и для Content-Security-Policy HTTP заголовка. Смотрите Использование политики содержимого для получения общего представления о синтаксисе для написания правил политики.

+ +

Примеры использования ключа могут включать в себя:

+ + + +

При написании правил по защите содержимого, вы имеете некоторые ограничения:

+ + + +

Примеры

+ +

Работающие примеры

+ +

Разрешает загрузку скриптов из "https://example.com": (смотрите примечание 1)

+ +
"content_security_policy": "script-src 'self' https://example.com; object-src 'self'"
+ +

Разрешает загрузку скриптов из любого субдомена "jquery.com":

+ +
"content_security_policy": "script-src 'self' https://*.jquery.com; object-src 'self'"
+ +

Разрешает использование eval() и его товарищей:

+ +
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';"
+ +

Разрешает встроить скрипт: "<script>alert('Hello, world.');</script>":

+ +
"content_security_policy": "script-src 'self' 'sha256-qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng='; object-src 'self'"
+ +

Оставляет изначальные правила, но так же требует, чтобы могли загружаться только изображения, запакованные вместе с расширением:

+ +
"content_security_policy": "script-src 'self'; object-src 'self'; img-src 'self'"
+ +

Разрешает загрузку только тех ресурсов, которые были запакованы вместе с расширением:

+ +
"content_security_policy": "default-src 'self'"
+
+ +

Недопустимые примеры

+ +

Политика, не включающая "object-src" директиву:

+ +
"content_security_policy": "script-src 'self' https://*.jquery.com;"
+ +

Политика, не включающая ключевое слово "self" в "script-src" директиве:

+ +
"content_security_policy": "script-src https://*.jquery.com; object-src 'self'"
+ +

Использование отличной от https схемы для загрузки удалённых ресурсов:

+ +
"content_security_policy": "script-src 'self' http://code.jquery.com; object-src 'self'"
+ +

Использование универсального символа в связке с публичным доменным суффиксом:

+ +
"content_security_policy": "script-src 'self' https://*.blogspot.com; object-src 'self'"
+ +

Указание схемы без хоста:

+ +
"content_security_policy": "script-src 'self' https:; object-src 'self'"
+ +

Использование неподдерживаемого ключевого слова 'unsafe-inline':

+ +
"content_security_policy": "script-src 'self' 'unsafe-inline'; object-src 'self'"
+ +

1. Примечание: Работающие примеры демонстрируют правильное написание политики защиты содержимого. Тем не менее, расширения с политикой, включающей ключевые словами 'unsafe-eval', 'unsafe-inline', разрешающей загрузку удалённых скриптов и ресурсов, а так же blob файлов не будут допущены к распространению на addons.mozilla.org из-за значительных проблем с безопасностью.

+ +

Browser compatibility

+ + + +

{{Compat("webextensions.manifest.content_security_policy")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/description/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/description/index.html new file mode 100644 index 0000000000..46c7310329 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/description/index.html @@ -0,0 +1,44 @@ +--- +title: description +slug: Mozilla/Add-ons/WebExtensions/manifest.json/description +tags: + - Reference + - WebExtensions + - description +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/description +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
ТипString
ОбязательныйНет
Пример +
+"description": "Заменяет картинки на картинки с котиками."
+
+ +

Краткое описание дополнения, предназначенное для показа в интерфейсе браузера.

+ +

Это локализуемое свойство.

+ +

Пример

+ +
"description": "Заменяет картинки на картинки с котиками."
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.description")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/icons/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/icons/index.html new file mode 100644 index 0000000000..4352adba81 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/icons/index.html @@ -0,0 +1,80 @@ +--- +title: ключ icons +slug: Mozilla/Add-ons/WebExtensions/manifest.json/icons +tags: + - Icons + - WebExtensions + - Веб-расширение + - Дополнения + - Расширения +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
ТипObject
ОбязательныйНет
Пример +
+"icons": {
+  "48": "icon.png",
+  "96": "icon@2x.png"
+}
+
+ +

Ключ icons определяет, какие иконки (значки) будет использовать ваше дополнение. Эти иконки будут использоваться при показе вашего дополнения в менеджерах компонентов, таких как Менеджер Дополнений.

+ +

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

+ +

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

+ +

Вы должны указать по крайней мере одну главную иконку, в идеале размером 48х48 пикселей. Эта иконка будет использоваться по умолчанию в Менеджере Дополнений. Конечно, можно добавить иконки любого размера, и Firefox постарается найти лучшую из них для показа в разных компонентах.

+ +

Firefox учитывает разрешение экрана, когда выбирает иконку. Чтобы получить наилучший результат на мониторах с большим разрешением, использующих технологию Retina display, добавьте для каждой иконки версию с размерами в два раза больше.

+ +

Пример

+ +

Ключи в объекте icons определяют размеры иконок в пикселях, значения - относительный путь к файлам с изображениями. Этот пример содержит иконку размером 48х48 пикселей и увеличенную версию для мониторов высокого разрешения.

+ +
"icons": {
+  "48": "icon.png",
+  "96": "icon@2x.png"
+}
+ +

SVG

+ +

В качестве иконки можно использовать файл SVG. Тогда браузер будет масштабировать иконку так, чтобы она подходила к компоненту, в котором она используется. Но есть два предостережения:

+ +
    +
  1. В файле изображения должен быть определён viewBox. Например: +
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    +
  2. +
  3. Даже в том случае, если используется всего один файл, нужно определить его для разных размеров иконки в манифесте. Например: +
    "icons": {
    +  "48": "icon.svg",
    +  "96": "icon.svg"
    +}
    +
  4. +
+ +
+

Если вы используете программу Inkscape или подобную ей для создания SVG, сохраняйте изображение как "Простой SVG". Иначе Firefox может запутаться во множестве специальных пространств имён и не отобразить картинку.

+
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.icons")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/index.html new file mode 100644 index 0000000000..661cf31e12 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/index.html @@ -0,0 +1,139 @@ +--- +title: manifest.json +slug: Mozilla/Add-ons/WebExtensions/manifest.json +tags: + - WebExtensions + - manifest.json + - Веб-расширения + - Дополнения + - Обзор + - Расширения +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json +--- +

{{AddonSidebar}}

+ +
+

В этой статье описан файл manifest.json для веб-расширений. Если Вы ищете информацию о manifest.json для Прогрессивных веб-приложений (PWAs), смотрите статью Манифест веб-приложения.

+
+ +

Файл manifest.json это единственный файл, который обязательно должен быть в каждом расширении, использующем API Веб-расширения (WebExtension APIs).

+ +

Используя manifest.json, Вы определяете базовые метаданные о расширении, такие как имя и версия. Также можно определить некоторые аспекты функционала (такие, как фоновые скрипты, контент скрипты и действия браузера).

+ +

Это файл в формате JSON, но в нём можно использовать комментарии, каждая строка которых должна начинаться с "//".

+ +

Список полей manifest.json

+ +

Поддерживаемые manifest.json поля перечислены ниже:

+ +
{{ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}
+ +

Примечания о полях manifest.json

+ + + +

Доступ к полям manifest.json во время выполнения

+ +

C помощью функции JavaScript {{WebExtAPIRef("runtime.getManifest()")}} можно получить доступ к файлу манифеста расширения:

+ +
browser.runtime.getManifest().version;
+ +

Пример

+ +

В следующем блоке показан основной синтаксис некоторых часто используемых полей манифеста.

+ +
+

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

+
+ +

Если нужны примеры готовых расширений, смотрите Примеры расширений.

+ +
{
+  "browser_specific_settings": {
+    "gecko": {
+      "id": "addon@example.com",
+      "strict_min_version": "42.0"
+    }
+  },
+
+  "background": {
+    "scripts": ["jquery.js", "my-background.js"],
+  },
+
+  "browser_action": {
+    "default_icon": {
+      "19": "button/geo-19.png",
+      "38": "button/geo-38.png"
+    },
+    "default_title": "Whereami?",
+    "default_popup": "popup/geo.html"
+  },
+
+  "commands": {
+    "toggle-feature": {
+      "suggested_key": {
+        "default": "Ctrl+Shift+Y",
+        "linux": "Ctrl+Shift+U"
+      },
+      "description": "Send a 'toggle-feature' event"
+    }
+  },
+
+  "content_security_policy": "script-src 'self' https://example.com; object-src 'self'",
+
+  "content_scripts": [
+    {
+      "exclude_matches": ["*://developer.mozilla.org/*"],
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ],
+
+  "default_locale": "en",
+
+  "description": "...",
+
+  "icons": {
+    "48": "icon.png",
+    "96": "icon@2x.png"
+  },
+
+  "manifest_version": 2,
+
+  "name": "...",
+
+  "page_action": {
+    "default_icon": {
+      "19": "button/geo-19.png",
+      "38": "button/geo-38.png"
+    },
+    "default_title": "Whereami?",
+    "default_popup": "popup/geo.html"
+  },
+
+  "permissions": ["webNavigation"],
+
+  "version": "0.1",
+
+  "user_scripts": {
+    "api_script": "apiscript.js",
+  },
+
+  "web_accessible_resources": ["images/my-image.png"]
+}
+ +

Совместимость с браузерами

+ +

Для полного обзора всех полей манифеста и их содержимого, смотрите полную таблицу совместимости manifest.json с браузерами.

+ + + +

{{Compat("webextensions.manifest")}}

+ +

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

+ +

{{WebExtAPIRef("permissions")}} JavaScript API

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/manifest_version/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/manifest_version/index.html new file mode 100644 index 0000000000..1cf7875003 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/manifest_version/index.html @@ -0,0 +1,45 @@ +--- +title: ключ manifest_version +slug: Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version +tags: + - Reference + - WebExtensions + - manifest_version +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version +--- +

{{AddonSidebar}}

+ + + + + + + + + + + + + + + + +
ТипNumber
ОбязательныйДа
Пример +
+"manifest_version": 2
+
+ +

Этот ключ определяет версию файла "manifest.json", использующуюся в этом дополнении.

+ +

В настоящее время всегда должен быть 2

+ +

Пример

+ +
"manifest_version": 2
+
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.manifest_version")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/name/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/name/index.html new file mode 100644 index 0000000000..59c50eafdd --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/name/index.html @@ -0,0 +1,44 @@ +--- +title: ключ name +slug: Mozilla/Add-ons/WebExtensions/manifest.json/name +tags: + - Reference + - WebExtensions + - name +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/name +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
ТипString
ОбязательныйДа
Пример +
+"name": "My Extension"
+
+ +

Имя расширения. Используется для идентификации расширения в интерфейсе браузера и на сайтах, подобных addons.mozilla.org.

+ +

Это локализуемое свойство.

+ +

Пример

+ +
"name": "My Extension"
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.name")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/permissions/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/permissions/index.html new file mode 100644 index 0000000000..bfe2556a86 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/permissions/index.html @@ -0,0 +1,193 @@ +--- +title: permissions +slug: Mozilla/Add-ons/WebExtensions/manifest.json/permissions +tags: + - Web-расширение + - Полномочия + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/permissions +--- +

{{AddonSidebar}}

+ + + + + + + + + + + + + + + + +
ТипМассив
ОбязателенНет
Пример +
+"permissions": [
+  "*://developer.mozilla.org/*",
+  "webRequest"
+]
+
+ +

Используйте ключ permissions для получения дополнительных возможностей для вашего расширения. Значением ключа является массив строк, каждая из которых представляет собой запрос на какие-либо полномочия.

+ +

При объявлении запросов полномочий с помощью этого ключа, браузер проинформирует пользователей, о том какие полномочия необходимы расширению во время его установки, и задаст вопрос, согласны ли они выдать их расширению. Браузер так же даёт пользователям возможность изучить полномочия расширения уже после установки. Так как требование дополнительных полномочий может повлиять на желание пользователя использовать ваше расширение, решение использования конкретного функционала может стоить тщательного рассмотрения. К примеру, есть смысл избегать запрашивания необязательных полномочий, и предоставлять информацию о том, зачем вашему расширению нужны какие-либо полномочия в описании расширения. Более подробная информация о проблемах, которые вам стоит рассмотреть касательно этой темы, предоставлена в статье Запрашивание правильных полномочий.

+ +

Значение ключа может содержать три вида запросов полномочий:

+ + + +

Запрос полномочий для хоста

+ +

Запрос на полномочия для хоста объявляется через шаблоны совпадения, где каждый шаблон определяет группу URL, при посещении которых расширение будет иметь эти дополнительные полномочия. Например, запрос на полномочия для хоста может быть задан подобной строкой "*://developer.mozilla.org/*".

+ +

Полномочия для хоста включают:

+ + + +

В Firefox, начиная с версии 56, расширения автоматически получают полномочия для своего собственного хоста, который имеет вид:

+ +
moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/
+ +

где 60a20a9b-1ad4-af49-9b6c-c64c98c37920 - внутреннее ID расширения. Расширение может получить это URL программным путём, через вызов метода extension.getURL():

+ +
browser.extension.getURL("");
+// moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/
+
+ +

Запрос на API полномочия

+ +

Запрос на API полномочия объявляется через ключевые слова, каждое из которых представляет собой название WebExtension API, доступ к которому необходим расширению.

+ +

Следующие ключевые слова доступны на данный момент:

+ + + +

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

+ + + +

Запрос на activeTab полномочия

+ +

Этот вид запроса объявляется через ключевое слово "activeTab". activeTab полномочия предоставляются расширению на активной в данный момент вкладке, и вступают в эффект только в момент, когда пользователь взаимодействует с расширением.

+ +

"Взаимодействие пользователя" включает:

+ + + +

activeTab полномочия включают:

+ + + +

Цель этих полномочий – позволить расширению выполнять наиболее распространенные сценарии работы, без необходимости выдавать ему более серьёзные привилегии, так как большинство расширений задумано для выполнения какой-либо работы на активной вкладке после взаимодействия с пользователем. Например, представьте расширение, которое встраивает скрипт на текущую страницу, после того как пользователь нажимает на кнопку расширения на панели инструментов. Если бы activeTab полномочий не существовало, расширению бы пришлось запрашивать <all_urls>. Но они бы давали расширению намного больше привилегий, чем ему было бы необходимо: расширение могло бы встраивать скрипты на любую вкладку и в любой момент, когда пожелает.

+ +

Заметьте, что вы сможете иметь доступ к привилегированному tab API, только на момент взаимодействия расширения с пользователем, и пока вкладка не изменила своё состояние. То есть расширение перестанет иметь данные привилегии при изменении адреса страницы или каком-либо другом событии с вкладкой.

+ +

Обычно вкладкой, получающей activeTab полномочия, является активная в данный момент вкладка, за исключением одного случая. menus API позволяет расширению создавать элементы контекстного меню, которые будут появляться непосредственно при нажатии на вкладку (элемент на панели вкладок, при нажатии на который изменяется активная вкладка). Если пользователь вызывает контекстное меню на этом элементе, тогда activeTab полномочия выдадутся для вкладки, по которой было произведено нажатие, несмотря на то, что она могла бы не является активной ({{bug(1446956)}} начиная с Firefox версии 63).

+ +

Доступ к буферу обмена

+ +

Два полномочия предоставляют расширению привилегии для взаимодействия с буфером обмена:

+ + + +

Смотрите Взаимодействие с буфером обмена для более подробной информации.

+ +

Неограниченное хранилище

+ +

Полномочие unlimitedStorage:

+ + + +

Примеры

+ +
 "permissions": ["*://developer.mozilla.org/*"]
+ +

Запрашивает полномочия для хостов, имеющих developer.mozilla.org в их URL.

+ +
  "permissions": ["tabs"]
+ +

Запрашивает доступ к привилегированным частям tabs API.

+ +
  "permissions": ["*://developer.mozilla.org/*", "tabs"]
+ +

Запрашивает несколько типов полномочий из примеров выше.

+ +

Browser compatibility

+ + + +

{{Compat("webextensions.manifest.permissions")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/manifest.json/version/index.html b/files/ru/mozilla/add-ons/webextensions/manifest.json/version/index.html new file mode 100644 index 0000000000..42892c82af --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/manifest.json/version/index.html @@ -0,0 +1,49 @@ +--- +title: ключ version +slug: Mozilla/Add-ons/WebExtensions/manifest.json/version +tags: + - Reference + - WebExtensions + - version +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/version +--- +

{{AddonSidebar}}

+ + + + + + + + + + + + + + + + +
ТипString
ОбязательныйДа
Пример +
+"version": "0.1"
+
+ +

Версия дополнения, отформатированная как числа и символы ASCII, разделенные точками. Подробнее о формате версий смотрите страницу Version format.

+ +

Обратите внимание, что синтаксис ключа version для Chrome более ограниченный, чем у Firefox:

+ + + +

Пример

+ +
"version": "0.1"
+ +

Совместимость с браузерами

+ + + +

{{Compat("webextensions.manifest.version")}}

diff --git a/files/ru/mozilla/add-ons/webextensions/match_patterns/index.html b/files/ru/mozilla/add-ons/webextensions/match_patterns/index.html new file mode 100644 index 0000000000..17ac749843 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/match_patterns/index.html @@ -0,0 +1,426 @@ +--- +title: Шаблоны совпадения в расширении +slug: Mozilla/Add-ons/WebExtensions/Match_patterns +translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns +--- +
{{AddonSidebar}}
+ +

Шаблоны совпадения - являются способом обозначения необходимых групп URL. Они используются в нескольких местах в WebExtensions API, главным образом для объявления какие веб-страницы должны загружать встраиваемые скрипты и по каким URL необходимо ожидать событий из  webRequest API.

+ +

API, которое использует шаблоны совпадения, обычно принимает их списками, и выполняет соответствующие действия, если URL имеет совпадение с одним из шаблонов. Например, взгляните на content_scripts ключ в manifest.json.

+ +

Структура шаблона совпадения

+ +
+

Заметьте: Некоторые браузеры не поддерживают определённые схемы.
+ Смотрите Browser compatibility table для дополнительной информации.

+
+ +

Все шаблоны совпадения объявляются в виде строк. За исключением специального <all_urls> шаблона, шаблоны совпадения состоят из трёх компонентов: схема, хост и путь. Схема и хост разделяются с помощью ://.

+ +
<схема>://<хост><путь>
+ +

Схема

+ +

Компонент схема может принимать один из двух видов:

+ + + + + + + + + + + + + + + + + + +
ВидСовпадение
*Только "http" and "https", так же "ws" и "wss" в некоторых браузерах.
Одно из http, https, ws, wss, ftp, ftps, data или file.Только данная схема.
+ +

Хост

+ +

Компонент хост может принимать один из трёх видов:

+ + + + + + + + + + + + + + + + + + + + + + +
FormMatches
*Любой хост.
*. за которыми следует частичное имя хоста.Данный хост и любые его субдомены.
Полное название хоста без *.Только данный хост.
+ +

Хост не должен включать в себя значение порта.

+ +

Хост не обязателен, если схема задана, как "file".

+ +

Заметьте, что * звёздочка (символ универсального значения) может быть написана только в начале строки.

+ +

Путь

+ +

Компонент путь должен начинаться с / символа.

+ +

Вслед за ним он может иметь любую комбинацию символов и * звёздочек, которые позволено использовать для обозначения URL и строки параметров (начинается после ?). В отличии от хоста, путь может содержать * звёздочку в середине или в конце строки, и * звёздочка может появляться в строке более одного раза.

+ +

Значение пути сравнивается со строкой, которая представляет из себя URL и строку параметров. Если строка параметров присутствует в URL, тогда она отделяется от основного URL знаком ?. Если вы хотите иметь соответствие с URL на любом домене, где URL путь кончается на foo.bar, не зависимо от присутствия строки параметров, тогда вам нужно иметь массив шаблонов совпадений, например ['*://*/*foo.bar', '*://*/*foo.bar?*']. В этой ситуации необходимо использовать ?*, а не bar*, для того чтобы обозначить, что * будет применяться к строке параметров, а не к основной части URL пути.

+ +

Ни идентификатор якоря, ни предшествующая ему #, не считаются частями пути.

+ +

<all_urls>

+ +

Специальное значение <all_urls> совпадает со всеми URL, если они используются со следующими схемами: "http", "https", "ws", "wss", "ftp", "data", and "file".

+ +

Примеры

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ШаблонПример совпаденияПример несовпадения
+

<all_urls>

+ +

Совпадение со всеми URL.

+
+

http://example.org/

+ +

https://a.org/some/path/

+ +

ws://sockets.somewhere.org/

+ +

wss://ws.example.com/stuff/

+ +

ftp://files.somewhere.org/

+ +

ftps://files.somewhere.org/

+
+

resource://a/b/c/
+ (неподдерживаемая схема)

+
+

*://*/*

+ +

Совпадение со всеми HTTP, HTTPS и WebSocket URL.

+
+

http://example.org/

+ +

https://a.org/some/path/

+ +

ws://sockets.somewhere.org/

+ +

wss://ws.example.com/stuff/

+
+

ftp://ftp.example.org/
+ (несовпадающая схема)

+ +

ftps://ftp.example.org/
+ (несовпадающая схема)

+ +

file:///a/
+ (несовпадающая схема)

+
+

*://*.mozilla.org/*

+ +

Совпадение со всеми HTTP, HTTPS и WebSocket URL, которые находятся на "mozilla.org" или одном из её субдоменов.

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

http://a.mozilla.org/

+ +

http://a.b.mozilla.org/

+ +

https://b.mozilla.org/path/

+ +

ws://ws.mozilla.org/

+ +

wss://secure.mozilla.org/something

+
+

ftp://mozilla.org/
+ (несовпадающая схема)

+ +

http://mozilla.com/
+ (несовпадающий хост)

+ +

http://firefox.org/
+ (несовпадающий хост)

+
+

*://mozilla.org/

+ +

Совпадение со всеми HTTP, HTTPS и WebSocket URL, которые находятся исключительно на "mozilla.org/".

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

ws://mozilla.org/

+ +

wss://mozilla.org/

+
+

ftp://mozilla.org/
+ (несовпадающая схема)

+ +

http://a.mozilla.org/
+ (несовпадающий хост)

+ +

http://mozilla.org/a
+ (несовпадающий путь)

+
+

ftp://mozilla.org/

+ +

Совпадение только с "ftp://mozilla.org/".

+
ftp://mozilla.org +

http://mozilla.org/
+ (несовпадающая схема)

+ +

ftp://sub.mozilla.org/
+ (несовпадающий хост)

+ +

ftp://mozilla.org/path
+ (несовпадающий путь)

+
+

https://*/path

+ +

Совпадение со всеми HTTPS URL на любом хосте, чей путь точно соответсвует "path".

+
+

https://mozilla.org/path

+ +

https://a.mozilla.org/path

+ +

https://something.com/path

+
+

http://mozilla.org/path
+ (несовпадающая схема)

+ +

https://mozilla.org/path/
+ (несовпадающий путь)

+ +

https://mozilla.org/a
+ (несовпадающий путь)

+ +

https://mozilla.org/
+ (несовпадающий путь)

+ +

https://mozilla.org/path?foo=1
+ (несовпадающий путь из-за строки параметров)

+
+

https://*/path/

+ +

Совпадение со всеми HTTPS URL на любом хосте, чей путь точно соответсвует "path/" и не имеет строки параметров.

+
+

https://mozilla.org/path/

+ +

https://a.mozilla.org/path/

+ +

https://something.com/path/

+
+

http://mozilla.org/path/
+ (несовпадающая схема)

+ +

https://mozilla.org/path
+ (несовпадающий путь)

+ +

https://mozilla.org/a
+ (несовпадающий путь)

+ +

https://mozilla.org/
+ (несовпадающий путь)

+ +

https://mozilla.org/path/?foo=1
+ (несовпадающий путь из-за строки параметров)

+
+

https://mozilla.org/*

+ +

Совпадение со всеми HTTPS URL только на домене "mozilla.org", с любым URL путём и строкой параметров.

+
+

https://mozilla.org/

+ +

https://mozilla.org/path

+ +

https://mozilla.org/another

+ +

https://mozilla.org/path/to/doc

+ +

https://mozilla.org/path/to/doc?foo=1

+
+

http://mozilla.org/path
+ (несовпадающая схема)

+ +

https://mozilla.com/path
+ (несовпадающий хост)

+
+

https://mozilla.org/a/b/c/

+ +

Совпадение только с данным URL, или данным URL, имеющим идентификатор якоря.

+
+

https://mozilla.org/a/b/c/

+ +

https://mozilla.org/a/b/c/#section1

+
Всё остальное.
+

https://mozilla.org/*/b/*/

+ +

Совпадение только с HTTPS URL, которые находятся на "mozilla.org", чей путь имеет сегмент "b" где-то в середине. Совпадёт с URL со строкой параметров, если эта строка параметров заканчивается на /.

+
+

https://mozilla.org/a/b/c/

+ +

https://mozilla.org/d/b/f/

+ +

https://mozilla.org/a/b/c/d/

+ +

https://mozilla.org/a/b/c/d/#section1

+ +

https://mozilla.org/a/b/c/d/?foo=/

+ +

https://mozilla.org/a?foo=21314&bar=/b/&extra=c/

+
+

https://mozilla.org/b/*/
+ (несовпадающий путь)

+ +

https://mozilla.org/a/b/
+ (несовпадающий путь)

+ +

https://mozilla.org/a/b/c/d/?foo=bar
+ (несовпадающий путь из-за строки параметров)

+
+

file:///blah/*

+ +

Совпадает с любым FILE URL, чей путь начинается с "blah".

+
+

file:///blah/

+ +

file:///blah/bleh

+
file:///bleh/
+ (несовпадающий путь)
+ +

Недопустимые шаблоны совпадения

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Недопустимый шаблонПричина
resource://path/Неподдерживаемая схема.
https://mozilla.orgОтсутствие пути.
https://mozilla.*.org/"*" в хосте должна присутствовать только в начале.
https://*zilla.org/"*" в хосте должен быть единственным символом или сопровождаться  ".".
http*://mozilla.org/"*" в схеме должен быть единственным символом.
https://mozilla.org:80/Хост не должен включать в себя номер порта.
*://*Пустой путь: должно быть переписано, как "*://*/*".
file://*Пустой путь: должно быть переписано, как "file:///*".
+ +

Browser compatibility

+ +

scheme

+ + + +

{{Compat("webextensions.match_patterns.scheme",10)}}

diff --git a/files/ru/mozilla/add-ons/webextensions/prerequisites/index.html b/files/ru/mozilla/add-ons/webextensions/prerequisites/index.html new file mode 100644 index 0000000000..e18158e724 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/prerequisites/index.html @@ -0,0 +1,8 @@ +--- +title: Prerequisites +slug: Mozilla/Add-ons/WebExtensions/Prerequisites +translation_of: Mozilla/Add-ons/WebExtensions/Prerequisites +--- +
{{AddonSidebar}}
+ +

Всё что вам нужно - это Firefox 45 или выше. Смотрите Your first WebExtension для того чтобы начать.

diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/browser_action/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/browser_action/index.html new file mode 100644 index 0000000000..ba7e259817 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/browser_action/index.html @@ -0,0 +1,50 @@ +--- +title: Кнопка в панели инструментов +slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +tags: + - Кнопка панели инструментов +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +--- +
{{AddonSidebar}}
+ +

Кнопка на панели инструментов браузера (оригинальное название browser action) - это иконка, которую можно вывести в панель инструментов. Пользователь взаимодействует с расширением нажимая на нее как на кнопку.
+

+ +

Кнопка на панели инструментов одинаково отображается для любой открытой вкладки. Это предполагает, что расширение единообразно работает со всеми страницами.

+ +

Например, предустановленная кнопка "обновить" перезагружает любую страницу в активной вкладке, кнопка "добавить в избранное" добавляет любой адрес активной вкладки в список избранного. Кнопка загрузок показывает единый для всего браузера список скачанных файлов, независимо от того что за страница открыта в активной вкладке.

+ +

Применимые лишь к определенным страницам кнопки следует реализовывать с помощью кнопки в адресной строке (page action).

+ +

Объявление в manifest.json

+ +

За кнопку на панели инструментов отвечает свойство манифеста  browser_action:

+ +
"browser_action": {
+  "default_icon": {
+    "19": "button/geo-19.png",
+    "38": "button/geo-38.png"
+  },
+  "default_title": "Whereami?"
+}
+ +

Свойство кнопки default_icon обязательно, оно определяет внешний вид кнопки - иконку, которая окажется на панели инструментов.

+ +

Расширение может иметь только одну кнопку для панели инструментов.

+ +

Возможны два способа реакции на нажатие кнопки: отображение всплывающего окна (описано в отдельном разделе) или отправка события в background script расширения. В таком случае реакция на нажатие обеспечивают обработчики событий, подключенные к browserAction.onClicked:

+ +
browser.browserAction.onClicked.addListener(handleClick);
+ +

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

+ +

Все свойства кнопки на панели инструментов можно изменить программно через API browserAction.

+ +

Примеры

+ +

В GitHub репозитории webextensions-examples представлены несколько примеров расширений, которые создают кнопку на панели инструментов:

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html new file mode 100644 index 0000000000..229d378a2f --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html @@ -0,0 +1,54 @@ +--- +title: Контекстное меню +slug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items +--- +
+
{{AddonSidebar}}
+ +
+

Эта возможность пользовательского интерфейса позволяет добавлять новые элементы в контекстное меню браузера, появляющееся при нажатии правой кнопки мыши. Вкладки браузера также имеют контекстное меню доступное через browser.menus API.

+ +

Example of content menu items added by a WebExtension, from the context-menu-demo example

+ +

Возможность добавления элементов в контекстное меню позволяет предоставлять пользователю различные функции в зависимости от его действий на странице или в браузере. Например, можно отобразить элемент, который открывает графический редактор, если пользователь нажимает на изображение, или же предложить функцию для сохранения содержимого страницы, если выбрана некоторая её часть. Элементы могут представлять из себя не только текст, но и, например, кнопку-переключатель или разделитель (см. типы элементов меню). После того, как элемент контекстного меню был добавлен с помощью {{WebExtAPIRef("contextMenus.create")}}, он отображается во всех вкладках браузера, но вы можете удалить его при помощи {{WebExtAPIRef("contextMenus.remove")}}.

+
+
+ +

Создание элементов контекстного меню

+ +

Управление элементами контекстного меню осуществляется с помощью {{WebExtAPIRef("contextMenus")}} API. Однако, вам необходимо указать разрешение contextMenus в manifest.json, чтобы им воспользоваться.

+ +
"permissions": ["contextMenus"]
+ +

Затем вы сможете добавлять, обновлять и удалять элементы контекстного меню в фоновом сценарии вашего расширения. Для создания элемента необходимо указать его id, заголовок и контекст, в котором элемент будет показан. В примере ниже элемент меню появляется, когда выделен текст или какая-либо другая часть страницы:

+ +
browser.contextMenus.create({
+  id: "log-selection",
+  title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
+  contexts: ["selection"]
+}, onCreated);
+ +

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

+ +
browser.contextMenus.onClicked.addListener(function(info, tab) {
+  switch (info.menuItemId) {
+    case "log-selection":
+      console.log(info.selectionText);
+      break;
+    ...
+  }
+})
+ +

Иконки

+ +

Чтобы добавить элементам меню икноки, смотрите документацию Iconography в Photon Design System.

+ +

Примеры

+ +

Репозиторий webextensions-examples на GitHub содержит два примера расширений, в которых реализована работа элементов контекстного меню:

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html new file mode 100644 index 0000000000..fdb63f2252 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html @@ -0,0 +1,73 @@ +--- +title: Страницы расширения +slug: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages +tags: + - UI + - WebExtensions + - Веб-расширения + - Для начинающих +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages +--- +
{{AddonSidebar()}}
+ +

В расширение можно добавить HTML-страницы, чтобы предоставить пользователю формы, помощь или другое необходимое содержимое.

+ +

Example of a simple bundled page displayed as a detached panel.

+ +

Эти страницы получат доступ к привилегированным средствам JavaScript API — таким же как те, что доступны фоновым скриптам расширения. Но каждая из них будет открыта в своей отдельной вкладке — со своей очередью задач JavaScript, своими глобальными переменными и т. д.

+ +

Фоновую страницу можно считать "невидимой страницей расширения".

+ +

Определение страниц расширения

+ +

К расширению можно подключить файлы HTML и используемые в них файлы CSS и JavaScript. Можно расположить все эти файлы в корне папки расширения, а можно организовать более сложную структуру каталога.

+ +
/my-extension
+    /manifest.json
+    /my-page.html
+    /my-page.js
+ +

Отображение страниц расширения

+ +

Есть два способа отобразить страницу расширения: {{WebExtAPIRef("windows.create()")}} и {{WebExtAPIRef("tabs.create()")}}.

+ +

Например для того, чтобы создать окно сообщения, можно с помощью функции windows.create() открыть страницу HTML в отсоединённой панели (detached panel) — в окне без строки адреса, полосы закладок и других обычных элементов управления:

+ +
let createData = {
+  type: "detached_panel",
+  url: "panel.html",
+  width: 250,
+  height: 100
+};
+let creating = browser.windows.create(createData);
+ +

Когда окно больше не будет нужно, его можно закрыть программно.

+ +

Например, когда пользователь нажмёт на кнопку, можно вызвать функцию {{WebExtAPIRef("windows.remove()")}} и передать ей идентификатор текущего окна:

+ +
document.getElementById("closeme").addEventListener("click", function(){
+  let winId = browser.windows.WINDOW_ID_CURRENT;
+  let removing = browser.windows.remove(winId);
+}); 
+ +

Страницы расширения и история

+ +

По умолчанию страницы, открытые таким образом, будут сохранены в истории браузера — точно так же, как и обычные веб-страницы. Если такое поведение не нужно, используйте {{WebExtAPIRef("history.deleteUrl()")}}, чтобы удалить запись:

+ +
function onVisited(historyItem) {
+  if (historyItem.url == browser.extension.getURL(myPage)) {
+    browser.history.deleteUrl({url: historyItem.url});
+  }
+}
+
+browser.history.onVisited.addListener(onVisited);
+ +

Для использования API истории браузера нужно добавить разрешение "history" с помощью элемента permissions в файле manifest.json.

+ +

Дизайн веб-страницы

+ +

Подробности о том, как сделать, чтобы дизайн Ваших страниц совпадал со стилем Firefox, смотрите на сайте Система дизайна Photon (на английском языке) и в документации browser styles.

+ +

Примеры

+ +

В репозитории webextensions-examples на GitHub есть пример window-manipulator, в котором используются некоторые из возможностей для создания окон.

diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/index.html new file mode 100644 index 0000000000..c35b6146c6 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/index.html @@ -0,0 +1,107 @@ +--- +title: Пользовательский интерфейс +slug: Mozilla/Add-ons/WebExtensions/user_interface +tags: + - Пользовательский интерфейс +translation_of: Mozilla/Add-ons/WebExtensions/user_interface +--- +
{{AddonSidebar}}
+ +

У расширений WebExtensions есть несколько органов взаимодействия с пользователем, с их помощью человек пользуется расширенным функционалом. Все они перечислены ниже, с инструкцией как использовать в своем расширении каждый из них.

+ +
+

Советы как с помощью этих элементов пользовательского интерфейса (UI) обеспечить отличное взаимодействие человека с программой вы найдёте в статье User experience best practices.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Элемент UIНазначениеКак выглядит?
Кнопка на панели инструментов +

Кнопка на панели инструментов доступна изо всех вкладок.
+ Реакцию на нажатие кнопки обеспечивает расширение.

+
Example of a WebExtension toolbar button
+

Browser toolbar button with a popup

+
+

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

+
+

Example of a WebExtension toolbar button with a popup

+
Кнопка в адресной строкеВ отличие от панели инструментов, в адресной строке кнопка должна появляться только рядом с адресом предназначенной для нее страницы.Example showing an address bar button (page action)
Всплывающие окнаПри нажатии на кнопку всплывает (popup) web-страница с органами управления.Example of a popup on the address bar button
Контекстное менюОрганы управления могут быть упорядочены в ветвящейся структуре контекстных меню браузера.
Боковая панель +

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

+
Example of a WebExtension's sidebar
Страница настройки дополнения +

Страница пользовательских настроек доступна из меню управления дополнениями единообразно для всех расширений.

+
Example showing the options page content added in the favorite colors example.
Дополнительные веб-страницы +

Некоторые варианты содержимого (например, справку или форму обратной связи) удобнее расположить на дополнительной web-странице, которая открывается в собственной вкладке или окне.

+
Example of a simple bundled page displayed as a detached panel.
Уведомления +

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

+
Example notification from a WebExtension
Угадывание адреса по мере вводаПредлагать настраиваемые варианты адресной строки при вводе пользователем ключевого слова.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Панели инструмента разработчикаВкладка со связанным HTML-документом, который отображается в инструментах разработчика браузера.New panel tab in the Developer Tools tab bar
+ +

В следующих руководствах приведены пошаговые инструкции по созданию некоторых из этих параметров пользовательского интерфейса:

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/notifications/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/notifications/index.html new file mode 100644 index 0000000000..4bb1099110 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/notifications/index.html @@ -0,0 +1,51 @@ +--- +title: Уведомления +slug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications +tags: + - Web-расширение + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications +--- +
{{AddonSidebar}}
+ +
+

Уведомления позволяют вам передавать информацию пользователям вашего расширения через службу уведомлений в операционной системе.

+ +

+ +

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

+ +

Управление уведомлениями

+ +

Управление уведомлениями происходит программным путём с помощью  {{WebExtAPIRef("notifications")}} API. Для использования этого API вы должны иметь notifications полномочия в manifest.json:

+ +
"permissions": ["notifications"]
+ +

После этого вы можете использовать {{WebExtAPIRef("notifications.create")}} для создания ваших уведомлений, как, например, в нижеприведённом коде, взятом из  notify-link-clicks-i18n:

+ +
var title = browser.i18n.getMessage("notificationTitle");
+var content = browser.i18n.getMessage("notificationContent", message.url);
+browser.notifications.create({
+  "type": "basic",
+  "iconUrl": browser.extension.getURL("icons/link-48.png"),
+  "title": title,
+  "message": content
+});
+ +

Этот код создаёт уведомление с иконкой, заголовком и сообщением.

+ +

Если уведомление имеет цель призвать пользователя к какому-либо действию, вы можете установить обработчик события на нажатия на уведомления:

+ +
browser.notifications.onClicked.addListener(handleClick);
+
+ +

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

+ +

Иконки

+ +

Смотрите статью Iconography в документации Photon Design System для получения информации по созданию иконок для уведомлений.

+ +

Примеры

+ +

Репозиторий образцов расширений webextensions-examples на GitHub включает в себя расширение notify-link-clicks-i18n, которое реализует систему уведомлений.

+
diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/omnibox/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/omnibox/index.html new file mode 100644 index 0000000000..cb7285ba92 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/omnibox/index.html @@ -0,0 +1,68 @@ +--- +title: Адресная строка +slug: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox +tags: + - Web-расширение + - Расширение +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox +--- +
{{AddonSidebar()}}
+ +

Используя {{WebExtAPIRef("omnibox")}} API, расширения могут взаимодействовать с адресной строкой и заполнять её выпадающий список предложений своими значениями, после введения пользователем определённого ключевого слова.

+ +

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

+ +

Это могло бы позволить вам написать расширение, которое, например, искало бы бесплатные книги в электронной библиотеке, или как в примере выше, строки кода из репозитория.

+ +

Настраивание взаимодействия с адресной строкой

+ +

Чтобы получить возможность взаимодействия с адресной строкой, вам необходимо добавить ключ omnibox в manifest.json файл, и присвоить ему значение в виде объекта, определяющего ключевое слово, после введения которого расширение активирует взаимодействие:

+ +
  "omnibox": { "keyword" : "cs" }
+ +

При желании, используя метод {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, вы можете изменить текст изначального предложения, которое всегда будет появляться первым в списке предложений адресной строки. Как вариант, оно может быть использовано для описания предоставляемого расширением функционала:

+ +
browser.omnibox.setDefaultSuggestion({
+  description: `Искать в кодовой базе firefox
+    (пример: "hello world" | "path:omnibox.js onInputChanged")`
+});
+ +

Далее, вы можете зарегистрировать обработчики на событие {{WebExtAPIRef("omnibox.onInputStarted")}}, которое будет распространяться после введения пользователем ключевого слова и нажатия на пробел, и на событие {{WebExtAPIRef("omnibox.onInputChanged")}}, которое будет распространяться при изменении пользователем строки адреса. Так же, с помощью обработчика события {{WebExtAPIRef("omnibox.onInputChanged")}}, вы будете иметь возможность заполнять выпадающий список своими предложениями. К примеру, в случае поиска кода на сайте https://searchfox.org/mozilla-central, используя введённые пользователем слова:

+ +
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
+  let headers = new Headers({"Accept": "application/json"});
+  let init = {method: 'GET', headers};
+  let url = buildSearchURL(text);
+  let request = new Request(url, init);
+
+  fetch(request)
+    .then(createSuggestionsFromResponse)
+    .then(addSuggestions);
+});
+ +

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

+ +

Чтобы обрабатывать нажатия пользователя на предложения из выпадающего списка, подпишитесь на событие {{WebExtAPIRef("omnibox.onInputEntered")}}. При нажатии на изначальное предложение в функцию обработчика будет передана набранная в данный момент строка адреса, во всех остальных случаях будет передаваться значение из выбранного предложения. Вторым аргументом в функцию обработчика будет передана информация из настроек браузера о том, каким образом пользователь предпочитает открывать новые ссылки. Например, в нижерасположенном коде, нажатие на изначальное предложение запустит поиск, тогда как нажатие на все остальные предложения просто откроет определённые них URL:

+ +
browser.omnibox.onInputEntered.addListener((text, disposition) => {
+  let url = text;
+  if (!text.startsWith(SOURCE_URL)) {
+    // Обновить url, если пользователь нажал на изначальное предложение.
+    url = `${SEARCH_URL}?q=${text}`;
+  }
+  switch (disposition) {
+    case "currentTab":
+      browser.tabs.update({url});
+      break;
+    case "newForegroundTab":
+      browser.tabs.create({url});
+      break;
+    case "newBackgroundTab":
+      browser.tabs.create({url, active: false});
+      break;
+  }
+});
+ +

Примеры

+ +

Репозиторий образцов расширений webextensions-examples на GitHub включает в себя расширение firefox-code-search, демонстрирующее взаимодействие с адресной строкой.

diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/popups/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/popups/index.html new file mode 100644 index 0000000000..23541f5a60 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/popups/index.html @@ -0,0 +1,50 @@ +--- +title: Всплывающие окна +slug: Mozilla/Add-ons/WebExtensions/user_interface/Popups +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups +--- +
{{AddonSidebar}}
+ +
+

A popup is a dialog that's associated with a toolbar button or address bar button.

+ +

+ +

When the user clicks the button, the popup is shown. When the user clicks anywhere outside the popup, the popup is closed. The popup can be closed programmatically by calling window.close() from a script running in the popup. However, you can't open the popup programmatically from an extension's JavaScript: it can only be opened in response to a user action.

+ +

You can define a keyboard shortcut that opens the popup using the "_execute_browser_action" and "_execute_page_action" shortcuts. See the documentation for the manifest.json key commands .

+ +

Specifying a popup

+ +

The popup is specified as an HTML file, which can include CSS and JavaScript files, as a normal web page does. Unlike a normal page, though, the JavaScript can use all the WebExtension APIs that the extension has permissions for.

+ +

The HTML file is included in the extension and specified as part of the browser_action or page_action key by "default_popup" in the manifest.json:

+ +
  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  }
+ +

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

+ +

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

+ +

Debugging popups

+ +

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

+ + + +

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

+ +

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

+ +

Examples

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use a browser action:

+ + +
diff --git a/files/ru/mozilla/add-ons/webextensions/user_interface/sidebars/index.html b/files/ru/mozilla/add-ons/webextensions/user_interface/sidebars/index.html new file mode 100644 index 0000000000..5a4f1e82f1 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/user_interface/sidebars/index.html @@ -0,0 +1,56 @@ +--- +title: Боковые панели (Sidebars) +slug: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars +tags: + - Sidebar + - Боковая панель +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars +--- +
{{AddonSidebar}}
+ +
+

Боковая панель - это панель, которая отображается в левой части окна браузера, рядом с веб-страницей. В браузере предусмотрен пользовательский интерфейс, который позволяет пользователю видеть доступные боковые панели и выбирать боковую панель для отображения. Например, Firefox имеет меню "Вид > Боковая панель". Одновременно может отображаться только одна боковая панель, и эта боковая панель будет отображаться для всех вкладок и всех окон браузера.

+ +

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

+ +

Используя ключ sidebar_action в manifest.json, расширение может добавить свою боковую панель в браузер. Она будет доступна наравне со встроенными панелями, и пользователь сможет открыть ее, используя тот же механизм, что и для встроенных боковых панелей.

+ +

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

+ +

Вы можете задать HTML документ для конкретной вкладки, используя функцию {{WebExtAPIRef("sidebarAction.setPanel()")}}. Боковая панель может определить, к какому окну она принадлежит используя {{WebExtAPIRef("windows.getCurrent()")}} API:

+ +
// sidebar.js
+browser.windows.getCurrent({populate: true}).then((windowInfo) => {
+  myWindowId = windowInfo.id;
+});
+ +

Это полезно, если боковая панель хочет отображать различный контент для разных окон. Использование такого подхода см. в примере "annotate-page" example.

+ +

HTML документ боковай панели получает доступ к тому же набору привилегированных JavaScript API, что и background и  popup сценарии этого расширения. Они могут получить прямой доступ к фоновой странице с помощью {{WebExtAPIRef("runtime.getBackgroundPage()")}}, и могут взаимодействовать с сценариями контента или нативными приложениями, используя API интерфейса обмена сообщениями, такие как {{WebExtAPIRef("tabs.sendMessage()")}} и {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

+ +

Документы боковой панели выгружаются, когда окно браузера закрывается или пользователь закрывает боковую панель. Это означает, что в отличие от background страниц документы боковой панели не остаются загруженными все время, но в отличие от popup окон они остаются загруженными, пока пользователь взаимодействует с веб-страницами.

+ +

После первой установки расширения, использующего боковую панель, его панель будет открыта автоматически. Это сделано для того, чтобы помочь пользователю понять, что расширение использует боковую панель. Обратите внимание, что расширение не может открывать боковые панели программно: боковые панели могут открываться только пользователем.

+ +

Использование боковых панелей

+ +

Чтобы использовать боковую панель в своем расширении, укажите с помощью ключа sidebar_action в manifest.json key, HTML-документ панели, а также заголовок и значок по умолчанию:

+ +
"sidebar_action": {
+  "default_title": "My sidebar",
+  "default_panel": "sidebar.html",
+  "default_icon": "sidebar_icon.png"
+}
+ +

Вы можете изменить название и значок панели программно, используя {{WebExtAPIRef("sidebarAction")}} API.

+ +

Заголовок и значок отображаются пользователю в любом UI, предоставляемом браузером, для отображения боковых панелей, например меню "Вид > Боковые панели" в Firefox.

+ +

Примеры

+ +

В репозитории webextensions-examples на GitHub содержится несколько примеров расширений, которые используют боковую панель:

+ + +
diff --git a/files/ru/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/ru/mozilla/add-ons/webextensions/what_are_webextensions/index.html new file mode 100644 index 0000000000..ff947610ee --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/what_are_webextensions/index.html @@ -0,0 +1,95 @@ +--- +title: Что такое WebExtensions? +slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +tags: + - Extensions + - WebExtensions + - Дополнения + - Расширения +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +
{{AddonSidebar}}
+ +
+

Дополнения расширяют и изменяют функциональность браузера. Они разрабатываются с использованием стандартных Веб-технологий - JavaScript, HTML и CSS, а также некоторых специальных JavaScript API, которые позволяют вам делать намного больше, чем то, на что вы способны на любом из сайтов. Вот некоторые из примеров того, что вы можете делать:

+
+ +
+

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

+
+ +
Пример использования Amazon Assistant for Firefox
+ +
+

Примеры: Amazon Assistant for Firefox, OneNote Web Clipper и Grammarly for Firefox.

+
+ +
+

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

+
+ +
Как расширение может изменить фоновую картинку сайта
+ +
+

Примеры: MyWeb New Tab, Tabliss и VivaldiFox.

+
+ +
+

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

+
+ +
Как работает uBlock Origin, популярный блокировщик рекламы
+ +
+

Примеры: uBlock Origin, Reader и Toolbox for Google Play Store™.

+
+ +
+

Дайте новые инструменты и функции: Добавляйте новые пункты в список дел или генерируйте QR-коды для текста страницы или различных ссылок. При помощи гибких опций интерфейса и мощью WebExtensions API вы можете с лёгкостью добавлять новые функции в браузер. Причём вы можете расширить таким образом функциональность любого сайта, он не обязательно должен быть вашим.

+
+ +
Как выглядит генератор QR-кодов QRUTILS.com
+ +
+

Примеры: Swimlanes for Trello и Tomato Clock.

+
+ +
+

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

+
+ +
Пример игры Asteroids in Popup
+ +
+

Примеры: Asteroids in Popup, Solitaire Card Game New Tab и 2048 Prime.

+
+ +
+

Добавляйте инструменты для разработки: Вы можете предлагать инструменты разработки как часть вашего бизнеса, или же как то, что вы нового открыли для веб-разработки и чем хотите поделиться. Например, вы можете добавлять свои инструменты во встроенный набор инструментов разработчика Firefox.

+
+ +
То, как интегрируется aXe в инструменты разработчика Firefox
+ +
+

Примеры: Web Developer, Web React Developer Tools и aXe Developer Tools.

+
+ +
+

WebExtensions - это кросс-браузерная система для разработки дополнений для браузера. В значительной степени ее API совместим с  extension API, который поддерживается браузерами Google Chrome и Opera. Расширения, разработанные для этих браузеров, в большинстве случаев будут работать в Firefox или Microsoft Edge с минимальными изменениями. Также API полностью совместим с мультипроцессным Firefox.

+
+ +
+

Мы также намерены расширять API для поддержки нужд разработчиков дополнений, и если у вас есть идеи, мы будем рады услышать их. Вы можете связаться с нами через рассылку  dev-addons mailing list или на IRC канале #webextensions.

+
+ +
+

До появления WebExtensions разработка дополнения для Firefox осуществлялась одним из трех различных способов: XUL/XPCOM overlays, bootstrapped extensions или Add-on SDK. В будущем WebExtensions станет рекомендуемым способом разработки дополнений для Firefox, а остальные способы будут считаться устаревшими.

+
+ +

Что дальше?

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/ru/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..e9e4e74784 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,191 @@ +--- +title: Ваш первый WebExtension +slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +tags: + - Beginner + - Extensions + - Guide + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +
{{AddonSidebar}}
+ +

В этой статье мы пройдем весь путь создания WebExtension для Firefox, от начала и до конца. Это дополнение будет просто добавлять красную рамку ко всем страницам, загруженным с "mozilla.org" или любого из его поддоменов.

+ +

Исходный код этого дополнения доступен на GitHub: https://github.com/mdn/webextensions-examples/tree/master/borderify.

+ +

Для начала вам нужен Firefox 45 или более поздней версии.

+ +

Написание WebExtension

+ +

Создайте новую директорию (папку) и перейдите в нее:

+ +
mkdir borderify
+cd borderify
+ +

manifest.json

+ +

Теперь создайте новый файл, назовите его "manifest.json" в папке "borderify". Вставьте туда следующий код:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Borderify",
+  "version": "1.0",
+
+  "description": "Adds a solid red border to all webpages matching mozilla.org.",
+  "icons": {
+    "48": "icons/border-48.png"
+  },
+
+  "applications": {
+    "gecko": {
+      "id": "borderify@mozilla.org",
+      "strict_min_version": "45.0"
+    }
+  },
+
+  "content_scripts": [
+    {
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ]
+
+}
+ + + +

Самый интересный ключ здесь - это content_scripts, который говорит Firefox загружать скрипт на Web страницах, чей URL совпадает с заданным шаблоном. В нашем случае, мы просим Firefox загрузить скрипт с названием "borderify.js" на всех HTTP или HTTPS страницах, полученных с "mozilla.org" или любого из его поддоменов.

+ + + +
+

В некоторых случаях вам нужно указать ID для вашего дополнения. Если вам нужно указать ID дополнения включите ключ applications в manifest.json и установите его свойство gecko.id:

+ +
"applications": {
+  "gecko": {
+    "id": "borderify@example.com"
+  }
+}
+
+ +

icons/border-48.png

+ +

Дополнение должно иметь иконку (значок). Эта иконка будет показана в списке дополнений в Менеджере Дополнений. Наш файл manifest.json сообщает, что иконка будет находиться в файле  "icons/border-48.png".

+ +

Создайте директорию (папку) "icons" внутри директории "borderify" . Сохраните в ней иконку под именем "border-48.png".  Вы можете использовать иконку из нашего примера, которая взята из набора иконок Google Material Design, и используется по лицензии Creative Commons Attribution-ShareAlike.

+ +

Вы можете использовать собственную иконку. Её размер должен быть 48x48 пикселей. Вы можете также использовать иконку размером 96x96 пикселей для отображения на мониторах высокого разрешения. В этом случае Вам необходимо указать её в качестве свойства "96" объекта "icons" в файле manifest.json:

+ +
"icons": {
+  "48": "icons/border-48.png",
+  "96": "icons/border-96.png"
+}
+ +

Также Вы можете создать иконку в формате SVG и она будет корректно масштабироваться.

+ + + +

borderify.js

+ +

Наконец, создайте в директории "borderify" файл с именем "borderify.js" и поместите туда следующий код:

+ +
document.body.style.border = "5px solid red";
+ +

Этот скрипт будет встраиваться в страницу, которая совпадает с шаблоном, указанном в ключе content_scripts файла manifest.json. Этот скрипт имеет прямой доступ ко всему документу, как если бы он был загружен самой страницей.

+ + + +

Пробуем

+ +

Сначала внимательно проверьте, что Вы правильно разместили файлы и дали им правильные имена:

+ +
borderify/
+    icons/
+        border-48.png
+    borderify.js
+    manifest.json
+ +

Установка

+ +

Начиная с версии Firefox 45 Вы можете временно установить WebExtension с локального диска.

+ +

Откройте страницу "about:debugging", кликните "Load Temporary Add-on" и выберите файл manifest.json:

+ +

{{EmbedYouTube("SKb-CNYpl6Q")}}

+ +

Теперь ваше дополнение установлено и останется в браузере до его перезапуска.

+ +

Для проверки, зайдите на страницу "about:addons" чтобы открыть Менеджер Дополнений. Вы должны увидеть своё дополнение с именем и иконкой:

+ +

{{EmbedYouTube("WpUL3-qmenE")}}

+ +

Также, Вы можете запускать WebExtension из командной строки, используя web-ext.

+ +

Тестирование

+ +

Теперь зайдите на любую страницу домена "mozilla.org" и вы должны будете увидеть красную границу вокруг страницы:

+ +

{{EmbedYouTube("exUAH0sIyBw")}}

+ +

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

+ +

{{EmbedYouTube("t6s_4yF8dRk")}}

+ +
+

Обратите внимание, что после изменения файла manifest.json, вы должны вручную перезагрузить своё дополнение. В настоящий момент это значит, что вам нужно перезагрузить Firefox, а затем снова загрузить своё дополнение на странице "about:debugging". Мы работаем над улучшением этого процесса. 

+
+ + + +

Упаковка и публикация

+ + + +

Чтобы другие люди могли использовать ваше дополнение, вам необходимо запаковать его. Дополнения Firefox в запакованном виде являются XPI файлами, которые представляют собой обычные ZIP архивы с расширением "xpi".

+ +

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

+ +

zip -r ../borderify.xpi *

+ +

Начиная с Firefox 43 все дополнения должны быть подписаны прежде чем они будут установлены в браузер. Вы можете снять это ограничение только в Firefox Developer Edition или  Firefox Nightly при помощи следующих шагов:  

+ + + +

{{EmbedYouTube("HgtBYDWtH4w")}}

+ + + +

Что дальше?

+ +

Теперь, когда вы имеете представление о разработке дополнений для Firefox, вы можете:

+ + diff --git a/files/ru/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/ru/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..db8eec8f90 --- /dev/null +++ b/files/ru/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,363 @@ +--- +title: Ваш второй WebExtension +slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +tags: + - Beginner + - Example + - Guide + - WebExtension +translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +--- +
{{AddonSidebar}} +

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

+ +

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

+ +

Чтобы реализовать это, мы:

+ + + +

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

+ +

+ +

Это простое дополнение, но показывает множество основных концепций WebExtensions API:

+ + + +

Вы можете найти полный исходный код дополнения на GitHub.

+ +

Чтобы написать это дополнение, Вам нужен Firefox 45 или новее.

+ +

Написание WebExtension

+ +

Создайте новую директорию и перейдите в нее:

+ +
mkdir beastify
+cd beastify
+ +

manifest.json

+ +

Теперь создайте файл "manifest.json" и вставьте в него следующее содержимое:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Beastify",
+  "version": "1.0",
+
+  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
+  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
+  "icons": {
+    "48": "icons/beasts-48.png"
+  },
+
+  "permissions": [
+    "activeTab"
+  ],
+
+  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  },
+
+  "web_accessible_resources": [
+    "beasts/frog.jpg",
+    "beasts/turtle.jpg",
+    "beasts/snake.jpg"
+  ]
+
+}
+
+ + + +

Обратите внимание, что все пути указаны относительно файла manifest.json.

+ +

Иконка

+ +

Дополнение должно иметь иконку. Она будет показана рядом с дополнением в Менеджере Дополнений (Вы можете открыть менеджер перейдя по ссылке "about:addons"). Наш manifest.json обещает, что у нас будет иконка для панели инструментов по адресу "icons/beasts-48.png".

+ +

Создайте папку "icons" и сохраните там иконку с именем "beasts-48.png". Вы можете использовать иконку из нашего примера, которая взята из набора Aha-Soft’s Free Retina и используется на условиях этой лицензии.

+ +

Если Вы выберете свою иконку, она должна быть размером 48x48 пикселей. Вы также можете предоставить иконку размером 96x96 пикселей для дисплеев с высоким разрешением, определив свойство "96" объекта icons в файле manifest.json:

+ +
"icons": {
+  "48": "icons/beasts-48.png",
+  "96": "icons/beasts-96.png"
+}
+ +

Кнопка панели инструментов

+ +

Кнопка панели инструментов также нуждается в иконке, и наш manifest.json обещает, что у нас будет иконка для панели инструментов по адресу "icons/beasts-32.png".

+ +

Сохраните иконку с именем "beasts-32.png" в папке "icons". Вы можете использовать иконку из нашего примера, которая взята из набора IconBeast Lite и используется на условиях этой лицензии.

+ +

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

+ +

Всплывающая панель

+ +

Функция панели - позволить пользователю выбрать одного из трех зверей.

+ +

Создайте новую папку с именем "popup" в корневой папке дополнения. Здесь мы сохраним код для панели. Панель будет состоять из трех файлов:

+ + + +

choose_beast.html

+ +

HTML выглядит так:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+    <link rel="stylesheet" href="choose_beast.css"/>
+  </head>
+
+  <body>
+    <div class="button beast">Frog</div>
+    <div class="button beast">Turtle</div>
+    <div class="button beast">Snake</div>
+    <div class="button clear">Reset</div>
+
+    <script src="choose_beast.js"></script>
+  </body>
+
+</html>
+ +

У нас есть элемент для каждого животного. Обратите внимание, что мы подключаем CSS и JS файлы из HTML файла, как на обыкновенной веб-странице.

+ +

choose_beast.css

+ +

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

+ +
html, body {
+  width: 100px;
+}
+
+.button {
+  margin: 3% auto;
+  padding: 4px;
+  text-align: center;
+  font-size: 1.5em;
+  cursor: pointer;
+}
+
+.beast:hover {
+  background-color: #CFF2F2;
+}
+
+.beast {
+ background-color: #E5F2F2;
+}
+
+.clear {
+ background-color: #FBFBC9;
+}
+
+.clear:hover {
+ background-color: #EAEAC9;
+}
+
+ +

choose_beast.js

+ +

В JavaScript для всплывающего окна мы слушаем click события. Если click был на одном из трех вариантов наших животных, мы добавляем content script в активную вкладку. После того, как content script загрузится, мы отправляем ему сообщение с выбранным животным:

+ +
/*
+Учитывая имя зверя, получаем URL соответствующего изображения.
+*/
+function beastNameToURL(beastName) {
+  switch (beastName) {
+    case "Frog":
+      return browser.extension.getURL("beasts/frog.jpg");
+    case "Snake":
+      return browser.extension.getURL("beasts/snake.jpg");
+    case "Turtle":
+      return browser.extension.getURL("beasts/turtle.jpg");
+  }
+}
+
+/*
+Слушаем события клика во всплывающей панели.
+
+Если кликнули одного из зверей:
+  Добавляем "beastify.js" к активной вкладке.
+
+  Затем получаем активную вкладку и отправляем сценарию "beastify.js"
+  сообщение, содержащее URL к картинке с выбранным зверем.
+
+Если кликнули кнопку, класс которой содержит "clear":
+  Перезагрузить страницу.
+  Закрыть всплывающую панель. Это необходимо, так как content script
+  неисправен после перезагрузки страницы.
+*/
+
+document.addEventListener("click", (e) => {
+  if (e.target.classList.contains("beast")) {
+    var chosenBeast = e.target.textContent;
+    var chosenBeastURL = beastNameToURL(chosenBeast);
+
+    browser.tabs.executeScript(null, {
+      file: "/content_scripts/beastify.js"
+    });
+
+    var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
+    gettingActiveTab.then((tabs) => {
+      browser.tabs.sendMessage(tabs[0].id, {beastURL: chosenBeastURL});
+    });
+  }
+  else if (e.target.classList.contains("clear")) {
+    browser.tabs.reload();
+    window.close();
+  }
+});
+
+ +

Скрипт использует три функции WebExtension API:

+ + + +

Сontent script

+ +

Создайте новую папку с именем "content_scripts" в корневой папке дополнения и создайте в ней новый файл с именем "beastify.js", со следующим кодом:

+ +
/*
+beastify():
+* удаляет каждый узел в document.body,
+* затем вставляет выбранного зверя
+* затем удаляется как слушатель
+*/
+function beastify(request, sender, sendResponse) {
+  removeEverything();
+  insertBeast(request.beastURL);
+  browser.runtime.onMessage.removeListener(beastify);
+}
+
+/*
+Удаляет каждый узел в document.body
+*/
+function removeEverything() {
+  while (document.body.firstChild) {
+    document.body.firstChild.remove();
+  }
+}
+
+/*
+Учитывая URL изображения зверя, создает и стилизует узел IMG,
+указывающий на это изображение, затем вставляет узел в документ.
+*/
+function insertBeast(beastURL) {
+  var beastImage = document.createElement("img");
+  beastImage.setAttribute("src", beastURL);
+  beastImage.setAttribute("style", "width: 100vw");
+  beastImage.setAttribute("style", "height: 100vh");
+  document.body.appendChild(beastImage);
+}
+
+/*
+Назначает beastify() слушателем сообщений расширения.
+*/
+browser.runtime.onMessage.addListener(beastify);
+
+ +

Content script добавляет слушателя к сообщениям от дополнения (в частности как в файле "choose_beast.js" выше). В слушателе скрипт:

+ + + +

Звери

+ +

Наконец, нам нужно подключить изображения животных.

+ +

Создайте новую папку с именем "beasts" и добавьте туда три изображения с соответствующими именами. Вы можете получить изображения из GitHub репозитория, или прямо здесь:

+ +

+ +

Тестирование

+ +

Во-первых, дважды проверьте, что у вас все файлы на своих местах:

+ +
beastify/
+
+    beasts/
+        frog.jpg
+        snake.jpg
+        turtle.jpg
+
+    content_scripts/
+        beastify.js
+
+    icons/
+        beasts-32.png
+        beasts-48.png
+
+    popup/
+        choose_beast.css
+        choose_beast.html
+        choose_beast.js
+
+    manifest.json
+ +

Начиная с Firefox 45 Вы можете временно установить дополнения с жесткого диска.

+ +

Откройте "about:debugging" в Firefox, кликните "Загрузить временное дополнение", и выберете Ваш файл manifest.json. После этого Вы должны увидеть иконку дополнения на панели инструментов Firefox:

+ +

{{EmbedYouTube("sAM78GU4P34")}}

+ +

Откройте веб-страницу, затем щелкните иконку, выберите зверя и посмотрите как страница изменится:

+ +

{{EmbedYouTube("YMQXyAQSiE8")}}

+ +

Разработка из командной строки

+ +

Вы можете автоматизировать этап временной установки используя web-ext. Попробуйте это:

+ +
cd beastify
+web-ext run
+
diff --git "a/files/ru/mozilla/add-ons/webextensions/\320\270\320\275\321\202\320\265\321\200\320\275\320\260\321\206\320\270\320\276\320\275\320\260\320\273\320\270\320\267\320\260\321\206\320\270\321\217/index.html" "b/files/ru/mozilla/add-ons/webextensions/\320\270\320\275\321\202\320\265\321\200\320\275\320\260\321\206\320\270\320\276\320\275\320\260\320\273\320\270\320\267\320\260\321\206\320\270\321\217/index.html" new file mode 100644 index 0000000000..36a37820d9 --- /dev/null +++ "b/files/ru/mozilla/add-ons/webextensions/\320\270\320\275\321\202\320\265\321\200\320\275\320\260\321\206\320\270\320\276\320\275\320\260\320\273\320\270\320\267\320\260\321\206\320\270\321\217/index.html" @@ -0,0 +1,405 @@ +--- +title: Интернационализация +slug: Mozilla/Add-ons/WebExtensions/Интернационализация +translation_of: Mozilla/Add-ons/WebExtensions/Internationalization +--- +
{{AddonSidebar}}
+ +

API WebExtensions предоставляет полезный модуль для интернационализации расширений — i18n. В этой статье мы рассмотрим его особенности и пример его работы. Система для расширений, построенных с помощью API WebExtension, i18n похожа на библиотеки JavaScript для i18n, такие как i18n.js.

+ +
+

Расширение, используемое в этой статье в качестве примера, — notify-link-clicks-i18n — доступно на GitHub. Читая последующие секции этой статьи, Вы можете исследовать его исходный код.

+
+ +

Структура интернализированного расширения

+ +

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

+ + + +

Давайте отдельно рассмотрим каждый элемент — последующие секции представляют собой шаги, которым стоит следовать во время интернационализации вашего расширения.

+ +

Добавление локализованных строк в _locales

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

Каждая система i18n требует предоставить строки во всех локализациях, которые Вы хотите поддерживать. В расширениях они хранятся в директории  _locales, размещенной внутри корневой директории. Строки каждой локализации (также называемые сообщениями) хранятся в файле messages.json, находящемся в поддиректории _locales, название которой - тег языка локализации.

+ +

Стоит заметить, что если тег включает в себя и базовый язык, и его региональный вариант, то по конвенции эти язык и вариант разделяются дефисом: например, "en-US". Однако в поддиректориях _locales, вместо дефиса используется нижнее подчеркивание: "en_US".

+ +

Таким образом, в нашем примере существую директории "en" (английский), "de" (немецкий), "nl" (голландский), and "ja" (японский). Внутри каждой из них находится файл messages.json .

+ +

Давайте рассмотрим структуру одного из этих файлов (_locales/en/messages.json):

+ +
{
+  "extensionName": {
+    "message": "Notify link clicks i18n",
+    "description": "Name of the extension."
+  },
+
+  "extensionDescription": {
+    "message": "Shows a notification when the user clicks on links.",
+    "description": "Description of the extension."
+  },
+
+  "notificationTitle": {
+    "message": "Click notification",
+    "description": "Title of the click notification."
+  },
+
+  "notificationContent": {
+    "message": "You clicked $URL$.",
+    "description": "Tells the user which link they clicked.",
+    "placeholders": {
+      "url" : {
+        "content" : "$1",
+        "example" : "https://developer.mozilla.org"
+      }
+    }
+  }
+}
+ +

Это стандартный файл JSON — каждый из его элементов является объектом с именем, содержащим сообщение (message) и описание (description). Оба предмета - строки; $URL$ — это заполнитель, который заменяется подстрокой, когда элемент notificationContent вызывается расширением. Вы научитесь это делать в секции {{anch("Получение сообщений из JavaScript")}}.

+ +
+

Примечание: Вы можете найти больше информации о структуре messages.json здесь.

+
+ +

Интернационализация manifest.json

+ +

Для интернационализации файла manifest.json нужно предпринять несколько шагов.

+ +

Получение локализованных строк в манифестах

+ +

Ваш файл manifest.json содержит строки, отображаемые пользователю, такие как имя и описание расширения. Если Вы интернационализируете эти строки и поместите их переводы в messages.json, то эти переводы будут отображаться пользователю в зависимости от локализации его браузера.

+ +

Чтобы интернационализировать строки, их нужно указывать следующим образом:

+ +
"name": "__MSG_extensionName__",
+"description": "__MSG_extensionDescription__",
+ +

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

+ +

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

+ +
    +
  1. Два подчеркивания
  2. +
  3. Строка "MSG"
  4. +
  5. Одно подчеркивание
  6. +
  7. Имя сообщения так как оно указано в messages.json
  8. +
  9. Два подчеркивания
  10. +
+ +
__MSG_ + messageName + __
+ +

Локализация по умолчанию

+ +

Еше одно поле. которое нужно указать в manifest.json — это default_locale:

+ +
"default_locale": "en"
+ +

Этот параметр устанавливает локализацию по умолчанию, используемую, если расширение не поддерживает локализацию браузера пользователя. Любые сообщения, недоступные в текущей локализации, будут браться из той локализации, которая установлена по умолчанию. There are some more details to be aware of in terms of how the browser selects strings — see {{anch("Выбор локализованной строки")}}.

+ +

CSS, зависящий от локализации

+ +

Локализованные строки также можно получить из CSS-файлов расширения. Например, Вы можете создать поля CSS, зависящие от локализации, так:

+ +
header {
+  background-image: url(../images/__MSG_extensionName__/header.png);
+}
+ +

Этот функционал может быть полезен, однако, возможно, для этих целей стоит использовать {{anch("Заранее определенные сообщения")}}.

+ +

Получение сообщений из JavaScript

+ +

Допустим, Вы добавили сообщения в Ваш manifest.json. Чтобы Ваше расширение начало использовать правильные языки, соответствующие сообщения следует вызывать при помощи JavaScript. API i18n достаточно прост и содержит всего 4 основных метода:

+ + + +

В нашем примере notify-link-clicks-i18n , фоновый скрипт содержит следующие строки:

+ +
var title = browser.i18n.getMessage("notificationTitle");
+var content = browser.i18n.getMessage("notificationContent", message.url);
+ +

Первая из них получает поле notificationTitle message из доступного файла messages.json, соответствующее наиболее подходящей локализации . Вторая строка похожа на первую, но в ней метод принимает URL в качестве второго параметра. Зачем? С помощью этого параметра мы указываем, на что нужно заменить заполнитель $URL$ в поле notificationContent message:

+ +
"notificationContent": {
+  "message": "You clicked $URL$.",
+  "description": "Tells the user which link they clicked.",
+  "placeholders": {
+    "url" : {
+      "content" : "$1",
+      "example" : "https://developer.mozilla.org"
+    }
+  }
+}
+
+ +

Объект "placeholders"  определяет все заполнители и то, откуда их нужно получать. Заполнитель "url" указывает, что информация о нем должна содержаться в $1 — первое значение, заданное внутри второго параметра getMessage(). Поскольку заролнитель называется "url",  $URL$ используется для его вызова внутри сообщения (то есть для заполнителя "name" нужно использовать $NAME$, и т. д.). Если Вы хотите задать значения нескольких заполнителей, их можно передавать во второй аргумент {{WebExtAPIRef("i18n.getMessage()")}} в виде массива — массив [a, b, c] передает значения $1, $2 и $3, и т. д. внутрь messages.json.

+ +

Давайте посмотрим на пример: изначально сообщение notificationContent в файле en/messages.json такое:

+ +
You clicked $URL$.
+ +

Пусть эта ссылка указывает на https://developer.mozilla.org. После вызова {{WebExtAPIRef("i18n.getMessage()")}}, содержание второго параметра становится доступно в messages.json в качестве значения $1, замещающего $URL$, так как это указано в заполнителе  "url". Таким образом, итоговое значение строки:

+ +
You clicked https://developer.mozilla.org.
+ +

Прямое использование заполнителей

+ +

Переменные ($1, $2, $3, и т. д.) можно вставлять напрямую в сообщения. Например, можно переписать объект "notificationContent" следующим образом:

+ +
"notificationContent": {
+  "message": "You clicked $1.",
+  "description": "Tells the user which link they clicked."
+}
+ +

Этот метод может показаться более быстрым и простым, но другой способ (использование "placeholders") считается лучшей практикой. Это вызвано тем, что имена заполнителей (например "url") и примеры помогают понять, что означают заполнители — через неделю после написания кода Вы, наверное, забудете, что обозначают заполнители $1$8, что менее вероятно, если заполнители именованы.

+ +

Заданные замены

+ +

Значения заполнителей можно задавать вручную, если Вы хотите, чтобы каждый раз это значение было одним и тем же, а не определялось переменной в коде. Например:

+ +
"mdn_banner": {
+  "message": "For more information on web technologies, go to $MDN$.",
+  "description": "Tell the user about MDN",
+  "placeholders": {
+    "mdn": {
+      "content": "https://developer.mozilla.org/"
+    }
+  }
+}
+ +

В этом примере мы сами задаем значение заполнителя, а не получаем его из переменной, такой как $1. Это может быть полезно, если сообщение очень сложное, и Вы хотите разделить значения, чтобы сделать строки более читаемыми. К тому же, доступ к этим значениям можно получить внутри программы.

+ +

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

+ +

Выбор локализованной строки

+ +

Локализации могут быть указаны с помощью кода языка, например fr или en. Они также могут содержать региональный код, например en_US или en_GB, описывающий региональный вариант языка. Когда вы запрашиваете строку у системы i18n, системы возвращает ее используя следующий алгоритм:

+ +
    +
  1. Если для текущей локализации существует файл messages.json, содержащий требуемую строку, возвращается она.
  2. +
  3. Иначе,если текущая локализация — региональный вариант (например en_US) и существует файл messages.json для этого языка, но без указания региона  (например en), содержащий строку, возвращается она.
  4. +
  5. Иначе, если существует файл messages.json для default_locale, указанной в manifest.json, и этот файл содержит нужную строку, возвращается она.
  6. +
  7. В противном случае возвращается пустая строка.
  8. +
+ +

Рассмотрим следующий пример:

+ + + +

Пусть default_locale установлен как fr, а текущая локализация браузера — en_GB:

+ + + +

Заранее определенные сообщения

+ +

Модуль i18n module предоставляет заранее определенные сообщения, которые можно вызвать таким же образом, как мы это делали в разделе {{anch("Интернационализация manifest.json")}}. Например:

+ +
__MSG_extensionName__
+ +

Заранее определенные сообщения используют такой же синтаксис, за исключением @@ перед именем сообщения, например:

+ +
__MSG_@@ui_locale__
+ +

Следующая таблица содержит различные заранее определенные сообщения:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Message nameDescription
@@extension_id +

Внутренний UUID расширения. Эту строку можно использовать для создания URL ресурсов внутри расширения.Даже нелокализованные расширения могут использовать это сообщения.

+ +

Это сообщения нельзя использовать в manifest.json.

+ +

Также стоит заметить, что этот ID — не ID аддона, которое возвращает {{WebExtAPIRef("runtime.id")}}, и которое может быть установлено с помощью ключа applications в manifest.json. Это сгенерированный UUID, содержащийся в URL аддона. Это означает, что данную величину нельзя использовать в качестве параметра extensionId  метода {{WebExtAPIRef("runtime.sendMessage()")}}, или для проверки поля id объекта {{WebExtAPIRef("runtime.MessageSender")}}.

+
@@ui_localeТекущая локализация; эту строку можно использовать для создания URL, зависящих от локализации.
@@bidi_dirНаправления чтения, либо "ltr" для языков, таких как английский, где текст читается слева направо, либо "rtl" для языков, считающихся справа налево, таких как арабский.
@@bidi_reversed_dirЕсли @@bidi_dir имеет значение "ltr", то возвращает "rtl"; иначе "ltr".
@@bidi_start_edgeЕсли @@bidi_dir имеет значение "ltr", то возвращает "left"; иначе "right".
@@bidi_end_edgeЕсли @@bidi_dir имеет значение "ltr", то возвращает "right"; иначе "left".
+ +

Возвращаясь к нашему примеру, лучше было бы написать:

+ +
header {
+  background-image: url(../images/__MSG_@@ui_locale__/header.png);
+}
+ +

Теперь мы можем хранить изображения в директориях поддерживаемых локализаций — en, de, и т. д. — что выглядит логичней.

+ +

Давайте рассмотрим пример использования сообщений @@bidi_* в файле CSS:

+ +
body {
+  direction: __MSG_@@bidi_dir__;
+}
+
+div#header {
+  margin-bottom: 1.05em;
+  overflow: hidden;
+  padding-bottom: 1.5em;
+  padding-__MSG_@@bidi_start_edge__: 0;
+  padding-__MSG_@@bidi_end_edge__: 1.5em;
+  position: relative;
+}
+ +

Для языков, в которых текст читается слева направо, таких как английский, правила CSS, использующие заранее определенные сообщения, сверху задают такие значения:

+ +
direction: ltr;
+padding-left: 0;
+padding-right: 1.5em;
+
+ +

Для языков, читающихся справа налево, значения будут следующими:

+ +
direction: rtl;
+padding-right: 0;
+padding-left: 1.5em;
+ +

Тестирование расширения

+ +

Начиная с Firefox 45, расширения могут быть временно установлены с диска — подробнее об этом написано в статье Loading from disk. Сделайте это и попробуйте протестировать наше расширение notify-link-clicks-i18n. Перейдите на одну из Ваших любимых страниц и нажмите на ссылку, чтобы проверить, появляется ли сообщения, содержащее URL нажатой ссылки.

+ +

Затем измените локализацию Firefox на какую-либо поддерживающуюся расширением, которое Вы хотите протестировать.

+ +
    +
  1. Откройте "about:config" в Firefox, и найдите параметр intl.locale.requested (обратите внимание на версию Firefox: в версиях до Firefox 59 этот параметр называется general.useragent.locale).
  2. +
  3. Если параметр существует, нажмите на него дважды (или нажмите Return/Enter), чтобы выбрать его, введите языковой код локализации, которую Вы хотите протестировать и нажмите "OK" (или Return/Enter). Например, в нашем примере расширение поддерживает "en" (английский), "de" (немецкий), "nl" (голландский), and "ja" (японский). Вы также можете указать пустую строку ("") в качестве значения. В этом случае браузер выберет язык Вашей ОС по умолчанию.
  4. +
  5. Если параметр intl.locale.requested не существует, нажмите правой кнопкой мыши на список параметров (или откройте контекстное меню при помощи клавиатуры), и выберите "New", а затем "String". Введите intl.locale.requested как имя настройки и, "de", "nl", и т. д. как значение, как это описано в шаге 2.
  6. +
  7. Найдите intl.locale.matchOS и, если параметр существует и равен true, дважды нажмите на него и установите на false.
  8. +
  9. Перезапустите браузер, чтобы изменения вступили в силу.
  10. +
+ +
+

Примечание: Этот метод работает, даже если у Вас не установлен языковой пакет для выбранного языка. В этом случае UI браузера просто будет использовать Ваш язык по умолчанию.

+
+ +
    +
+ +
+

Примечание: Чтобы изменить результат getUILanguage требуется языковой пакет, поскольку он отражает язык UI браузера, а не язык сообщений расширения.

+
+ +

Еше раз загрузите расширение с диска и протестируйте локализацию:

+ + + +

{{EmbedYouTube("R7--fp5pPGg")}}

diff --git "a/files/ru/mozilla/add-ons/webextensions/\320\274\320\276\320\264\320\270\321\204\320\270\320\272\320\260\321\206\320\270\321\217_\320\262\320\265\320\261_\321\201\321\202\321\200\320\260\320\275\320\270\321\206\321\213/index.html" "b/files/ru/mozilla/add-ons/webextensions/\320\274\320\276\320\264\320\270\321\204\320\270\320\272\320\260\321\206\320\270\321\217_\320\262\320\265\320\261_\321\201\321\202\321\200\320\260\320\275\320\270\321\206\321\213/index.html" new file mode 100644 index 0000000000..0f58364706 --- /dev/null +++ "b/files/ru/mozilla/add-ons/webextensions/\320\274\320\276\320\264\320\270\321\204\320\270\320\272\320\260\321\206\320\270\321\217_\320\262\320\265\320\261_\321\201\321\202\321\200\320\260\320\275\320\270\321\206\321\213/index.html" @@ -0,0 +1,238 @@ +--- +title: Модификация веб страницы +slug: Mozilla/Add-ons/WebExtensions/модификация_веб_страницы +translation_of: Mozilla/Add-ons/WebExtensions/Modify_a_web_page +--- +

 

+ +
{{AddonSidebar}}
+ +

Одним из наиболее распространённых вариантов использования расширений является внесение изменение в веб-страницу. К примеру, расширение может изменить стиль, применённый к странице, скрыть существующие или вставить на страницу дополнительные DOM-узлы.

+ +

Существует два способа сделать это используя WebExtensions API:

+ + + +

В любом случае, эти скрипты называются контентными скриптами, и отличаются от других скриптов, которые составляют расширение:

+ + + +

В этой статье мы рассмотрим оба способа загрузки скрипта.

+ +

Модификация страниц, подпадающих под URL-шаблон

+ +

Прежде всего создадим новую директорию, назовём её "modify-page". В этой директории, создадим файл "manifest.json", со следующим содержимым:

+ +
{
+
+  "manifest_version": 2,
+  "name": "modify-page",
+  "version": "1.0",
+
+  "content_scripts": [
+    {
+      "matches": ["https://developer.mozilla.org/*"],
+      "js": ["page-eater.js"]
+    }
+  ]
+
+}
+ +

Ключ content_scripts - это как мы загружаем скрипты на страницы, соответстующие URL-шаблону. В нашем случае, content_scripts говорит браузеру загрузить скрипт "page-eater.js" на все страницы, начинающиеся с https://developer.mozilla.org/.

+ +
+

Поскольку свойство "js" ключа content_scripts это массив, вы можете использовать его, для внедрения более одного скрипта. Если вы сделаете это, страницы получат набор, как если бы эти скрипты были загружены самой страницей, они будут загружены в той же очерёдности, в которой они расположены в массиве.

+
+ +
+

Ключ content_scripts также имеет свойство  "css", которое вы можете использовать для вставки CSS-таблиц.

+
+ +

Далее, создадим файл "page-eater.js", внутри директории "modify-page":

+ +
document.body.textContent = "";
+
+var header = document.createElement('h1');
+header.textContent = "Эта страница была съедена";
+document.body.appendChild(header);
+ +

Теперь установим расширение, и перейдём на страницу https://developer.mozilla.org/:

+ +

{{EmbedYouTube("lxf2Tkg6U1M")}}

+ +
+

Обратите внимание, несмотря на то, что в указанном видео, на странице addons.mozilla.org всё работает нормально, на текущий момент, для этого сайта, контентные скрипты заблокированы.

+
+ +

Программная модификация страницы

+ +

Что, если вы всё еще хотите "съедать" страницы, но лишь в тех случаях, когда пользователь попросил об этом? Давайте обновим этот пример таким образом, чтобы мы внедряли контентный скрипт, когда пользователь выбирает соответствующий пункт контентного меню.

+ +

Для начала обновим "manifest.json":

+ +
{
+
+  "manifest_version": 2,
+  "name": "modify-page",
+  "version": "1.0",
+
+  "permissions": [
+    "activeTab",
+    "contextMenus"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+
+}
+ +

Мы удалили ключ content_scripts и добавили два новых:

+ + + +

Давайте создадим этот файл. Создадим новый файл "background.js" в директории "modify-page" и поместим в него следующий код:

+ +
browser.contextMenus.create({
+  id: "eat-page",
+  title: "Съесть эту страницу"
+});
+
+browser.contextMenus.onClicked.addListener(function(info, tab) {
+  if (info.menuItemId == "eat-page") {
+    browser.tabs.executeScript({
+      file: "page-eater.js"
+    });
+  }
+});
+
+ +

В этом скрипте мы создаём элемент контекстного меню, передавая ему определённый идентификатор и заголовок (текст будет отображаться в элементе контекстного меню). Затем мы настраиваем обработчик событий таким образом, чтобы когда пользователь выбирает пункт контекстного меню, осуществлялась проверка, наш ли это элемент eat-page. Если это так - внедряем скрипт "page-eater.js" в текущую вкладку, используя tabs.executeScript() API. Это API опционально принимает идентификатор вкладки, в качестве аргумента. Мы опустили его, это означает, что скрипт будет внедряться в текущую активную вкладку.

+ +

На данном этапе расширение должно иметь следующий вид:

+ +
modify-page/
+    background.js
+    manifest.json
+    page-eater.js
+ +

Теперь перезагрузим расширение, откроем страницу (на этот раз любую) активируем контекстное меню и выберем "Съесть эту страницу":

+ +

{{EmbedYouTube("zX4Bcv8VctA")}}

+ +
+

Обратите внимание, несмотря на то, что в указанном видео, на странице addons.mozilla.org всё работает нормально, на текущий момент, для этого сайта, контентные скрипты заблокированы.

+
+ +

Обмен сообщениями

+ +

Контентные и фоновые скрипты не могут на прямую взаимодействовать друг с другом. Не смотря на это они могут взаимодействовать с помощью обмена сообщениями. Для этого один конец создаёт обработчик сообщений, а другой - может посылать сообщения. В следующей таблице представлены API-интерфейсы, задействованные с каждой стороны:

+ + + + + + + + + + + + + + + + + + + +
В контентном скриптеВ фоновом скрипте
Отправка сообщенияbrowser.runtime.sendMessage()browser.tabs.sendMessage()
Получение сообщенияbrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

Давайте обновим наш пример, чтобы посмотреть, как послать сообщение из фонового скрипта.

+ +

Изменим "background.js" :

+ +
browser.contextMenus.create({
+  id: "eat-page",
+  title: "Съесть эту страницу"
+});
+
+function messageTab(tabs) {
+  browser.tabs.sendMessage(tabs[0].id, {
+    replacement: "Message from the extension!"
+  });
+}
+
+browser.contextMenus.onClicked.addListener(function(info, tab) {
+  if (info.menuItemId == "eat-page") {
+    browser.tabs.executeScript({
+      file: "page-eater.js"
+    });
+
+    var querying = browser.tabs.query({
+      active: true,
+      currentWindow: true
+    });
+    querying.then(messageTab);
+  }
+});
+
+ +

Теперь, после внедрения "page-eater.js", мы используем tabs.query(), чтобы получить текущую открытую вкладку и используем tabs.sendMessage(), для отправки сообщения контентному скрипту, загруженному на этой вкладке. Сообщение несёт полезную нагрузку {replacement: "Message from the extension!"}.

+ +

Далее, обновим "page-eater.js":

+ +
function eatPage(request, sender, sendResponse) {
+  document.body.textContent = "";
+
+  var header = document.createElement('h1');
+  header.textContent = request.replacement;
+  document.body.appendChild(header);
+}
+
+browser.runtime.onMessage.addListener(eatPage);
+
+ +

Теперь, вместо простого "поедания страницы", контентный скрипт ждёт сообщение, используя runtime.onMessage. Когда сообщение получено, контентный скрипт выполняет в точности такой же код, как и а примере ранее, за исключением того, что заменяющий текст берётся из request.replacement.

+ +

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

+ +
+

Все эти примеры внедряют JavaScript; вы можете программно внедрять стилевые таблицы CSS используя функцию tabs.insertCSS().

+
+ +

Узнать больше

+ + diff --git "a/files/ru/mozilla/add-ons/webextensions/\320\277\320\265\321\200\320\265\320\262\320\276\320\264/index.html" "b/files/ru/mozilla/add-ons/webextensions/\320\277\320\265\321\200\320\265\320\262\320\276\320\264/index.html" new file mode 100644 index 0000000000..4ceb3eab28 --- /dev/null +++ "b/files/ru/mozilla/add-ons/webextensions/\320\277\320\265\321\200\320\265\320\262\320\276\320\264/index.html" @@ -0,0 +1,218 @@ +--- +title: Отладка +slug: Mozilla/Add-ons/WebExtensions/Перевод +tags: + - Firefox + - Mozilla + - Отладка + - Пособие + - Предоставление Веб-страниц +translation_of: Mozilla/Add-ons/WebExtensions/Debugging +--- +
{{AddonSidebar}}
+ +
This article explains how you can use the Firefox developer tools to debug extensions built with WebExtension APIs.
+ +

An extension can consist of various different pieces — background scripts, popups, options pages, content scripts, sidebars — and you'll need to use a slightly different workflow to debug each piece. So each piece gets a top-level section in this article, and the intention is that these sections can be read in isolation. We'll begin by introducing the Add-on Debugger, which you'll use to debug most of the pieces of your extension.

+ + + +

The Add-on Debugger

+ +

For most of this article we'll use the Add-on Debugger. To open the Add-on Debugger:

+ + + +

You'll then see a new window open. The main Firefox window will be switched into the foreground, so you'll have to click on the new window to bring it in front.

+ +

{{EmbedYouTube("G2a65ewjfj0")}}

+ +

This new window is sometimes called a "toolbox" and contains the debugging tools we'll use. It has a tabbed interface: the row of tabs along the top lets you switch between the different tools:

+ +

+ +

In this article we'll use three debugging tools:

+ + + +

Debugging background scripts

+ +
+

The examples in this section use the "notify-link-clicks-l10n" example extension. If you'd like to play along, you can find this example in the webextensions-examples repository.

+
+ +

Background scripts stay loaded for the lifetime of the extension. They're loaded inside an invisible "background page": by default this is an empty HTML document, but you can specify your own HTML content using the "background" key in "manifest.json".

+ +

You can debug background scripts using the Add-on Debugger.

+ +

In the Add-on Debugger's Console you'll see logged output, including calls to console.log() from your own background scripts and any errors the browser raises as it executes them. Note that at the moment, the console shows all errors raised by the browser, not just errors related to your extensions code.

+ +

For example, the notify-link-clicks-i18n example extension logs a message from its background script when it receives a message from one of its content scripts:

+ +

{{EmbedYouTube("WDQsBU-rpN0")}}

+ +

Using the Console's command line, you can access and modify the objects created by your background scripts.

+ +

For example, here we call the notify() function defined in the extension's background script:

+ +

{{EmbedYouTube("g-Qgf8Mc2wg")}}

+ +

If you switch to the Debugger, you'll see all your extension's background scripts. You can set breakpoints, step through code, and do everything else you'd expect to be able to do in a debugger.

+ +

{{EmbedYouTube("MNeaz2jdmzY")}}

+ +

If you press the Escape key while you're in the Debugger, the toolbox will be split, with the bottom half now occupied by the Console. While you're at a breakpoint, you can now modify the program's state using the console. See Split console for more on this.

+ +

Debugging options pages

+ +

Options pages are HTML pages that the extension developer can supply, that contain options for the extension. They are typically displayed in an iframe in the Add-ons Manager (to see the Add-ons Manager, visit the "about:addons" page).

+ +

To debug options pages:

+ + + +

Any JavaScript sources it includes are then listed in the Debugger:

+ +

{{EmbedYouTube("BUMG-M8tFF4")}}

+ +
+

This video uses the favourite-colour example extension.

+
+ +

You'll also see any messages logged by your code in the Add-on Debugger's Console.

+ +

You can also use the Add-on Debugger to debug the page's HTML and CSS. First, though, you need to point the tools at the iframe that hosts the options page. To do this: open the options page, click the icon highlighted in the screenshot below, and select the options page from the drop-down list:

+ +

+ +

Now switch to the Inspector tab, and you'll be able to examine and edit HTML and CSS for the page:

+ +

{{EmbedYouTube("-2m3ubFAU94")}}

+ +

Debugging popups

+ +

Popups are dialogs that are attached to browser actions or page actions. They are specified using an HTML document that can include CSS and JavaScript sources for styling and behavior. Whenever the popup is visible, you can use the Add-on Debugger to debug its code.

+ +

One problem with popups is that if a popup is open and you click outside the popup, the popup is closed and its code is unloaded. This obviously makes them impossible to debug. To suppress this behavior, select Disable Popup Auto-Hide from the Elipsis menu as shown below:

+ +

+ +

Now, when you open a popup it will stay open until you press Escape.

+ +
+

Note: This change applies to built-in browser popups, like the Elipsis menu (...), as well as extension popups.

+ +

The setting does not persist across sessions. When you close the window, the setting reverts to auto-hide popups.

+Internally, this button just toggles the ui.popup.disable_autohide preference, which you can toggle manually using about:config.
+ +

When the popup is open, its JavaScript sources will be listed in the Debugger. You can set breakpoints and modify the program's internal state:

+ +

{{EmbedYouTube("hzwnR8qoz2I")}}

+ +
+

This video uses the beastify example extension.

+
+ +

You can also use the Add-on Debugger to debug the popup's HTML and CSS. First, though, you need to point the tools at the popup's document. To do this: open the popup, then click the icon highlighted in the screenshot below and select the popup's page from the drop-down list:

+ +

Now switch to the Inspector, and you'll be able to examine and edit the popup's HTML and CSS:

+ +

{{EmbedYouTube("6lvdm7jaq7Y")}}

+ +

Debugging content scripts

+ +

You can use the Add-on Debugger to debug background pages, options pages, and popups. However, you can't use it to debug content scripts. This is because, in multiprocess Firefox, content scripts run in a different process from the other parts of your extension. The browser console has similar limitations.

+ +

To debug content scripts attached to a web page, use the normal web developer tools for that page:

+ + + +

{{EmbedYouTube("f46hMLELyaI")}}

+ +

By default, the tools are shown attached to the bottom of browser tab, to reflect the fact that they are attached to this tab. You'll see any output from console.log() statements in your content scripts. You will also see your content scripts listed in the Debugger, where you'll be able to set breakpoints, step through the code, and so on.

+ +

{{EmbedYouTube("Hx3GU_fEPeo")}}

+ +
+

This video uses the notify-link-clicks-i18n example extension.

+
+ +
+

If the developer tools tab was not already open when the content script was injected, sometimes the content script is not listed in the debugger panel. If you experience this, reloading the page with the developer tools tab open should fix the problem.

+
+ +

Debugging sidebars

+ +

Sidebars are HTML pages opened as a sidebar in the browser UI that the extension developer can supply.

+ +

To debug sidebars:

+ + + +

Any JavaScript sources it includes are then listed in the Debugger.

+ +

You'll also see any messages logged by your code in the Add-on Debugger's Console.

+ +

You can also use the Add-on Debugger to debug the page's HTML and CSS. First, though, you need to point the tools at the iframe that hosts the options page. To do this: open the sidebar, click the icon highlighted in the screenshot below, and select the sidebar from the drop-down list:

+ +

+ +

Debug runtime permission requests

+ +

 

+ +

Runtime permissions granted in your extension are persistent. Therefore, if you want to test cases where the permission has not been granted you will need to add a feature to programmatically remove the permission, use the Extensions Permission Manager, or give your extension a new ID. For more information, see Retest runtime permission grants in Test permission requests.

+ +

 

+ +

Debugging developer tools pages & panels

+ +

Developer tools are extended by loading a hidden HTML page when devtools are opened and developer tools panels are HTML pages displayed as a developer tool in the browser UI that the extension developer can supply.

+ +

To debug the developer tools page:

+ + + +

To debug developer tools panels:

+ + + +

Any JavaScript sources it includes are then listed in the Debugger.

+ +

You'll also see any messages logged by your code in the Add-on Debugger's Console.

+ +

You can also use the Add-on Debugger to debug the page's HTML and CSS. First, though, you need to point the tools at the iframe that hosts the options page. To do this: open the sidebar, click the icon highlighted in the screenshot below, and select the sidebar from the drop-down list:

+ +

+ +

Debugging Browser Restarts

+ +

If your extension is active in ways that might be affected by the browser restarting, such as a session being restored, then you may want to do extra testing to ensure your code works as expected in those conditions.

+ +

See Testing persistent and restart features for more details.

diff --git "a/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" "b/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" new file mode 100644 index 0000000000..934e40e904 --- /dev/null +++ "b/files/ru/mozilla/add-ons/\320\267\320\260\320\263\321\200\321\203\320\267\320\276\321\207\320\275\321\213\320\265_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\321\217/index.html" @@ -0,0 +1,353 @@ +--- +title: Загружаемые расширения +slug: Mozilla/Add-ons/загрузочные_расширения +tags: + - Bootstrapped + - Extensions + - add-on + - Дополнения +translation_of: Archive/Add-ons/Bootstrapped_extensions +--- +
+

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

+
+ +

{{LegacyAddonsNotice}}{{AddonSidebar}}

+ +

{{ gecko_minversion_header("2.0") }}

+ +

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

+ +

Движок Gecko 2.0 {{ geckoRelease("2.0") }} вводит загружаемые расширения (bootstrapped extensions). Это специальные расширения, которые вместо использования наложения на интерфейс, сами програмно добавляют себя в приложение. Это делается запуском специального скрипта из файла, который включен в расширение и содержит функции, вызываемые браузером, для того чтобы установить, удалить, загрузить, выгрузить.

+ +

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

+ +

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

+ +

The startup and shutdown process

+ +

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

+ +

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

+ + + +

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

+ + + +

Notes on modifying the application user interface

+ +

chrome.manifest in bootstrapped add-ons

+ +

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

+ + + +

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

+ +

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

+ +

Adding user interface manually

+ +

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

+ +

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

+ +

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

+ +

Creating a bootstrapped extension

+ +

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

+ +
<em:bootstrap>true</em:bootstrap>
+ +

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

+ +

Backward compatibility

+ +

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

+ +

Bootstrap entry points

+ +

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

+ +

startup

+ +

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

+ +

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

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

shutdown

+ +

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

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

install

+ +

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

+ +
void install(
+  data,
+  reason
+);
+
+ +
Parameters
+ +
+
data
+
A bootstrap data structure.
+
reason
+
One of the reason constants, indicating why the extension is being installed. This will be one of ADDON_INSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.
+
+ +

uninstall

+ +

This function is called after the last call to shutdown() before a particular version of an extension is uninstalled.

+ +
Note: If you open the add-on manager and then click "Remove" on an add-on, it will not call uninstall function right away. This is a soft uninstall because of the available "Undo" option. If the add-on manager is closed or another event takes place such that the "Undo" option becomes unavailable, then the hard uninstall takes place and the uninstall function is called.
+ +
Note: The uninstall function fires on downgrade and upgrade as well so you should make sure it is an uninstall by doing this:
+function uninstall(aData, aReason) {
+if (aReason == ADDON_UNINSTALL) {
+console.log('really uninstalling');
+} else {
+console.log('not a permanent uninstall, likely an upgrade or downgrade');
+}
+}
+ +
void uninstall(
+  data,
+  reason
+);
+
+ +
Parameters
+ +
+
data
+
A bootstrap data structure.
+
reason
+
One of the reason constants, indicating why the extension is being uninstalled. This will be one of ADDON_UNINSTALL, ADDON_UPGRADE, or ADDON_DOWNGRADE.
+
+ +

Reason constants

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
APP_STARTUP1The application is starting up.
APP_SHUTDOWN2The application is shutting down.
ADDON_ENABLE3The add-on is being enabled.
ADDON_DISABLE4The add-on is being disabled. (Also sent during uninstallation)
ADDON_INSTALL5The add-on is being installed.
ADDON_UNINSTALL6The add-on is being uninstalled.
ADDON_UPGRADE7The add-on is being upgraded.
ADDON_DOWNGRADE8The add-on is being downgraded.
+ +

Bootstrap data

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
idstringThe ID of the add-on being bootstrapped.
versionstringThe version of the add-on being bootstrapped.
installPathnsIFileThe installation location of the add-on being bootstrapped. This may be a directory or an XPI file depending on whether the add-on is installed unpacked or not.
resourceURInsIURIA URI pointing at the root of the add-ons files, this may be a jar: or file: URI depending on whether the add-on is installed unpacked or not. {{ gecko_minversion_inline("7.0") }}
oldVersionstringThe previously installed version, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is install or startup. {{ gecko_minversion_inline("22.0") }}
newVersionstringThe version to be installed, if the reason is ADDON_UPGRADE or ADDON_DOWNGRADE, and the method is shutdown or uninstall. {{ gecko_minversion_inline("22.0") }}
+ +
+

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

+
+ +

Add-on debugger

+ +

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

+ +

Localization (L10n)

+ +

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

+ +

JS and JSM Files - Using Property Files

+ +

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

+ +

The absolute minimum needed here is:

+ +
    +
  1. File: install.rdf
  2. +
  3. File: chrome.manifest
  4. +
  5. File: bootstrap.js
  6. +
  7. Folder: locale +
      +
    1. Folder: VALID_LOCALE_HERE +
        +
      1. File: ANYTHING.properties
      2. +
      +
    2. +
    +
  8. +
+ +

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

+ +

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

+ +

XUL and HTML Files - Using Entities from DTD Files

+ +

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

+ +
    +
  1. You have to change the HTML file's extension to be .xhtml
  2. +
  3. The doctype must be defined point to a DTD file in your locale folder such as: <!DOCTYPE html SYSTEM "chrome://l10n/locale/mozilla.dtd">
  4. +
  5. Must add xmlns attribute to html tag for example: <html xmlns="http://www.w3.org/1999/xhtml">
  6. +
  7. If you have multiple DTD files read on here: Using multiple DTDs
  8. +
+ +

The bare minimum needed is:

+ +
    +
  1. File: install.rdf
  2. +
  3. File: chrome.manifest
  4. +
  5. File: bootstrap.js
  6. +
  7. Folder: locale +
      +
    1. Folder: VALID_LOCALE_HERE +
        +
      1. File: ANYTHING.dtd
      2. +
      +
    2. +
    +
  8. +
+ +

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

+ +

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

+ +

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

+ +

Further reading

+ + diff --git "a/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" "b/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" new file mode 100644 index 0000000000..4442856118 --- /dev/null +++ "b/files/ru/mozilla/add-ons/\321\200\320\265\320\272\320\276\320\274\320\265\320\275\320\264\320\260\321\206\320\270\320\270_\320\277\320\276_\320\277\320\276\320\262\321\213\321\210\320\265\320\275\320\270\321\216_\320\277\321\200\320\276\320\270\320\267\320\262\320\276\320\264\320\270\321\202\320\265\320\273\321\214\320\275\320\276\321\201\321\202\320\270_\321\200\320\260\321\201\321\210\320\270\321\200\320\265\320\275\320\270\320\271/index.html" @@ -0,0 +1,102 @@ +--- +title: Рекомендации по повышению производительности расширений +slug: Mozilla/Add-ons/Рекомендации_по_повышению_производительности_расширений +tags: + - Быстродействие + - Лучшие практики + - Плагины + - Производительность + - Расширения + - Руководство +translation_of: Archive/Add-ons/Performance_best_practices_in_extensions +--- +

Одно из самых значительных преимуществ браузера Firefox заключается в его чрезвычайной расширяемости. Благодаря дополнениям можно сделать практически что угодно. Есть и обратная сторона медали: плохо написанные расширения могут оказывать серьезное влияние на просмотр сайтов, в том числе и на производительность браузера Firefox в целом. Эта статья предлагает вашему вниманию лучшие практики и рекомендации, которые позволят повысить производительность и быстродействие не только вашего расширения, но также и самого браузера Firefox.

+ +

Увеличиваем скорость запуска

+ +

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

+ +

Загружайте только то, что вам действительно требуется

+ +

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

+ +

Используйте модули JavaScript

+ +

Вы можете создать собственный модуль JavaScript, объединив набор функций, которые нужны только в определенных ситуациях. Это упростит загрузку блоков кода вашего расширения на лету, вместо загрузки всего сразу.

+ +

Несмотря на то, что модули JavaScript могут быть чрезвычайно полезны и давать прирост производительности, они должны применяться разумно. Загрузка модулей все же несет небольшие затраты, поэтому разбивка кода на ненужные уровни может привести к негативным результатам. Код должен быть разбит на модули так, чтобы от этого улучшалась его понятность, а загрузка крупных или требующих больших затрат блоков кода могла быть значительно отсрочена.

+ +

Отсрочивайте все, что возможно

+ +

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

+ +

Если что-то можно сделать пусть даже на долю секунды позже, используйте методы {{ interface("nsITimer") }} или {{ domxref("window.setTimeout()") }} для того, чтобы отложить это действие на потом. Даже короткая отсрочка может иметь большое влияние на быстродействие.

+ +

Общие вопросы производительности

+ +

Избегайте утечек памяти

+ +

Утечки памяти вынуждают сборщик мусора и сборщик циклических ссылок (cycle collector) выполнять больший объем работы, а это в значительной мере сказывается на быстродействии.

+ +

Зомби-ячейки (zombie compartments) - это особый вид утечки памяти, который можно легко выявить. Загляните на страницу Зомби-ячейки, особенно раздел Проактивная проверка плагинов.

+ +

Ознакомьтесь с разделом Распространенные причины утечек памяти в расширениях, чтобы узнать, как избежать возникновения зомби-ячеек и других видов утечек.

+ +

Помимо поиска различных видов утечек памяти, стоит также проверить функционал вашего расширения и содержимое вкладки about:memory на предмет избыточного потребления памяти. Например, ошибка 719601 приводила к тому, что ячейка JavaScript содержала сотни мегабайт памяти, что гораздо больше, чем обычно.

+ +

Избегайте написания медленных таблиц стилей CSS

+ + + +

Избегайте использования технологии DOM Mutation Events

+ +

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

+ +

Используйте методы ленивой загрузки

+ +

JavaScript-модуль XPCOMUtils предоставляет два метрода ленивой (отложенной) загрузки:

+ + + +

Множество распространенных сервисов уже закэшированы для вас в модуле Services.jsm.

+ +

Используйте ассинхронный ввод/вывод

+ +

Это следует подчеркнуть: никогда не выполняйте синхронный ввод/вывод в главном потоке.

+ +

Любой ввод/вывод в главном потоке, будь то активность жесткого диска или сетевая активность, может стать причиной серьезных проблем с временем отклика интерфейса пользователя.

+ + + +

Избегайте событий перемещения мыши

+ +

Избегайте использования обработчиков событий мыши, включая такие события, как mouseover, mouseout, mouseenter, mouseexit, и особенно mousemove. Они возникают довольно часто, поэтому их обработчики способны в значительной мере повысить нагрузку на процессор.

+ +

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

+ +

Избегайте анимированных изображений

+ +

Анимированные изображения значительно более ресурсозатратны, чем считалось ранее, особенно когда используются в элементах {{ XULElem("tree") }}.

+ +

Рассмотрите возможность применения Chrome Workers

+ +

Вы можете использовать {{ domxref("ChromeWorker") }} для выполнения длительных задач или обработки данных.

+ +

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

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