diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 21:46:22 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 21:46:22 -0500 |
commit | a065e04d529da1d847b5062a12c46d916408bf32 (patch) | |
tree | fe0f8bcec1ff39a3c499a2708222dcf15224ff70 /files/ru/mozilla/add-ons | |
parent | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (diff) | |
download | translated-content-a065e04d529da1d847b5062a12c46d916408bf32.tar.gz translated-content-a065e04d529da1d847b5062a12c46d916408bf32.tar.bz2 translated-content-a065e04d529da1d847b5062a12c46d916408bf32.zip |
update based on https://github.com/mdn/yari/issues/2028
Diffstat (limited to 'files/ru/mozilla/add-ons')
32 files changed, 0 insertions, 5585 deletions
diff --git a/files/ru/mozilla/add-ons/add-on_guidelines/index.html b/files/ru/mozilla/add-ons/add-on_guidelines/index.html deleted file mode 100644 index 5be041195c..0000000000 --- a/files/ru/mozilla/add-ons/add-on_guidelines/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Add-on guidelines -slug: Mozilla/Add-ons/Add-on_guidelines -translation_of: 'https://extensionworkshop.com/documentation/publish/add-on-policies/' ---- -<p>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 <a class="external text" href="https://addons.mozilla.org/" rel="nofollow">AMO</a> are subject to <a href="https://addons.mozilla.org/developers/docs/policies" title="https://addons.mozilla.org/developers/docs/policies">additional policies</a>.</p> - -<h2 id="Be_Transparent">Be Transparent</h2> - -<ul> - <li>Add-ons must either be installed using the add-on web install system, or be approved by the user using the <a class="external text" href="https://blog.mozilla.org/addons/2011/08/11/strengthening-user-control-of-add-ons/" rel="nofollow">install opt-in dialog</a>. - - <ul> - <li>We want our users to know what they are installing so that they are not unpleasantly surprised by changes they did not expect. We also want them to know what to remove if they decide not to keep it.</li> - <li>Add-ons installed through application installers should <a class="external text" href="/en-US/docs/Adding_Extensions_using_the_Windows_Registry" rel="nofollow">use the Windows Registry</a> or equivalent global install methods so that Firefox displays the opt-in screen. The opt-in screen must not be tampered with in any way, including overlaying additional information or images on top of it.</li> - </ul> - </li> - <li>Add-ons must always be possible to uninstall or disable from the Add-ons Manager. - <ul> - <li>Add-ons installed globally using the Windows registry or global extension directories cannot be uninstalled (<a class="external text" href="https://bugzilla.mozilla.org/show_bug.cgi?id=640775" rel="nofollow">bug 640775</a>), but they can be disabled to the same effect.</li> - </ul> - </li> - <li>Add-ons must use a <a class="external text" href="/en-US/docs/Install_manifests#id" rel="nofollow">single unique ID</a> during their entire lifetime. - <ul> - <li>Using the same ID for multiple products, or multiple IDs for a single product, can lead to problems with automatic updates as well as blocklisting conflicts. Add-ons may change their IDs due to ownership changes, as they commonly use an email address-like format (<em>e.g.,</em> personasplus@mozilla.com).</li> - </ul> - </li> - <li>Add-ons must not use brand names, trademarks, or other terms in ways that deceive users. Using Mozilla trademarks must follow <a class="external text" href="http://www.mozilla.org/foundation/trademarks/policy.html" rel="nofollow">our trademark policy</a>.</li> - <li>Add-ons should clearly communicate their intended purpose and active features, including features introduced through updates. - <ul> - <li>While we understand and support add-on developers who choose to monetize their products, this should not come at the expense of users' browsing experience. If an add-on inserts advertisements, affiliate codes, sponsored search results, or the like, into web pages, the user should be made aware of this when the add-on is installed. Likewise, if some features require payment to use, or require payment to remain active after a trial period, users should be made aware of this.</li> - </ul> - </li> -</ul> - -<h2 id="Be_Respectful_to_Users">Be Respectful to Users</h2> - -<ul> - <li>Add-ons must remove all introduced code, executables, and application configuration changes when they are uninstalled. - <ul> - <li>Uninstalling an add-on using the regular uninstall process should generally suffice. This guideline primarily applies to changes made to preferences such as the homepage, default search URL, network settings, and so forth. These preferences should be restored to their previous values when the add-on is uninstalled. Most add-ons can easily accomplish this by making such changes via a <a class="external text" href="/en-US/docs/Building_an_Extension#Defaults_Files" rel="nofollow">default preferences file</a>.</li> - </ul> - </li> - <li>Add-ons should respect the users' choices and not make unexpected changes, or limit users' ability to revert them. - <ul> - <li>For instance, users generally do not expect an add-on to change the Firefox homepage. Asking users to opt-in to such extra changes is recommended. Making them difficult or impossible to revert is strongly discouraged.</li> - </ul> - </li> - <li>Add-ons should make it clear how private user data is being used. - <ul> - <li>Add-ons which send user data over the Internet should generally provide a Privacy Policy, ideally concise and easily readable.</li> - </ul> - </li> - <li>Add-on developers should provide a mechanism for them to be contacted. - <ul> - <li>While developers are not required to provide a support channel for users, it is recommended. All add-on developers should have a contact form or public email address so that they can be contacted in case of emergencies, such as guideline violations that could lead to blocklisting.</li> - </ul> - </li> -</ul> - -<h2 id="Be_Safe">Be Safe</h2> - -<ul> - <li>Add-ons must not cause harm to users' data, system, or online identities.</li> - <li>Add-ons must not transmit users' private data unsafely, or expose it to third parties unnecessarily. - <ul> - <li>Private data should always be sent over a secure connection. This includes browsing data such as visited URLs and bookmarks.</li> - <li>Making the browser easier to fingerprint by adding text to the User-Agent string or adding custom headers is also a privacy concern, and should be avoided.</li> - </ul> - </li> - <li>Add-ons must not create or expose application or system vulnerabilities. - <ul> - <li>Security bugs happen, but once discovered they need to be addressed immediately. A popular add-on with a security vulnerability is a valuable attack vector for hackers, and in such cases we will move quickly to blocklist the add-on if there is no prompt response from the developer.</li> - </ul> - </li> - <li>Add-ons must not tamper with the application or blocklist update systems.</li> - <li>Add-ons should not store any browsing data while in Private Browsing Mode. - <ul> - <li>It's worth stressing that PBM is about avoiding storing<em>local</em> data while browsing, not about sending data elsewhere. To learn more about PBM we recommend reading <a class="external text" href="http://ehsanakhgari.org/tag/privatebrowsing" rel="nofollow">Ehsan's blog posts</a> about it.</li> - </ul> - </li> -</ul> - -<h2 id="Be_Stable">Be Stable</h2> - -<ul> - <li>Add-ons must not cause hangs or crashes.</li> - <li>Add-ons should not break or disable core application features. - <ul> - <li>This includes features like tabbed browsing, Private Browsing Mode, and the location bar. Add-ons that are specifically meant to do this are exempt.</li> - </ul> - </li> - <li>Add-ons should not cause memory leaks, or unnecessarily consume large amounts of memory.</li> - <li>Add-ons should not slow down the application or system significantly.</li> - <li>Add-ons should not consume network resources to an extent that affects regular application usage. - <ul> - <li>Downloading large amounts of data without user awareness can significantly disrupt regular browsing, and may result in unexpected charges for users who have network usage limitations (notably on mobile).</li> - </ul> - </li> -</ul> - -<h2 id="Exceptions">Exceptions</h2> - -<ul> - <li>Add-ons can break some of these guidelines if that's their intended purpose and there isn't malicious intent (<em>e.g.,</em> a security exploit proof of concept).</li> - <li>Add-ons deployed by administrators within workplaces, schools, kiosks, and so forth, are exempt from most guidelines.</li> - <li>As add-ons can only run clean up code if they are uninstalled while Firefox is running and they are enabled, we do not require that they attempt to clean up after themselves when they are uninstalled under other circumstances. Application installers that configure Firefox without add-ons should revert any changes when uninstalled.</li> - <li>Add-ons may leave behind preferences changes in private preference branches which do not affect Firefox when the add-on is not active, so that any previous add-on configuration is not lost if the user decides to re-install the add-on in the future.</li> -</ul> - -<p>Other exceptions may apply.</p> - -<h2 id="Enforcement">Enforcement</h2> - -<p>Add-ons that do not follow these guidelines may qualify for blocklisting, depending on the extent of the violations. Guidelines qualified with the word<em>must</em> are especially important, and violations thereof will most likely result in a blocklisting nomination.</p> - -<p>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.</p> - -<p>Guideline violations should be <a class="external text" href="https://bugzilla.mozilla.org/enter_bug.cgi?product=Tech%20Evangelism&component=Add-ons" rel="nofollow">reported via Bugzilla</a>, under Tech Evangelism > Add-ons. Questions can be posted in the <a class="external text" href="irc://irc.mozilla.org/addons" rel="nofollow">#addons IRC channel</a>.</p> - -<p>These guidelines may change in the future. All updates will be announced in the <a class="external text" href="https://blog.mozilla.org/addons/" rel="nofollow">Add-ons Blog</a>.</p> diff --git a/files/ru/mozilla/add-ons/amo/index.html b/files/ru/mozilla/add-ons/amo/index.html deleted file mode 100644 index 0845e54e3d..0000000000 --- a/files/ru/mozilla/add-ons/amo/index.html +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: AMO -slug: Mozilla/Add-ons/AMO -tags: - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Add-ons/AMO ---- -<p>{{AddonSidebar}}</p> - -<p>Content to be added.</p> diff --git a/files/ru/mozilla/add-ons/amo/policy/index.html b/files/ru/mozilla/add-ons/amo/policy/index.html deleted file mode 100644 index 7baca9debb..0000000000 --- a/files/ru/mozilla/add-ons/amo/policy/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: AMO Policies -slug: Mozilla/Add-ons/AMO/Policy -tags: - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Add-ons/AMO/Policy ---- -<p>{{AddonSidebar}}</p> - -<p>Mozilla стремится обеспечить отличный опыт для наших пользователей и разработчиков надстроек. Перед отправкой своего дополнения ознакомьтесь с приведенными ниже правилами.</p> - - -<dl> - <dd></dd><dt><a href="/Mozilla/Add-ons/AMO/Policy/Agreement">Пакт о разработке</a></dt> -<dd>Effective January 5, 2016</dd> <dt><a href="/Mozilla/Add-ons/AMO/Policy/Reviews">Обзор процесса</a></dt> -<dd>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.</dd> <dt><a href="/Mozilla/Add-ons/AMO/Policy/Featured">Избранные дополнения</a></dt> -<dd>How up-and-coming add-ons become featured and what's involved in the process. </dd> <dt><a href="/Mozilla/Add-ons/AMO/Policy/Contact">Связаться с нами</a></dt> -<dd>Add-ons allow developers to extend and modify the functionality of Firefox.</dd> <br> - <strong><a href="https://developer.mozilla.org/en-US/Add-ons#Contact_us">Связаться с нами </a></strong><br> - Как связаться с нами в отношении этих политик или вашего дополнения. -</dl> diff --git a/files/ru/mozilla/add-ons/code_snippets/index.html b/files/ru/mozilla/add-ons/code_snippets/index.html deleted file mode 100644 index d7e42cd381..0000000000 --- a/files/ru/mozilla/add-ons/code_snippets/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Code snippets -slug: Mozilla/Add-ons/Code_snippets -tags: - - Add-ons - - Code snippets - - Extensions - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Code_snippets ---- -<p> </p> - -<div class="warning"> -<p>Дополнения с использованием методов, описанных в этом документе, считаются устаревшей технологией в Firefox. Не используйте эти методы для разработки новых дополнений. Используйте вместо этого <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions">WebExtensions</a>. Если вы поддерживаете надстройку, которая использует описанные здесь методы, рассмотрите возможность переноса ее на использование WebExtensions.</p> - -<p><strong>Начиная с <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 53</a>, никакие новые устаревшие дополнения не будут приниматься addons.mozilla.org (AMO) для Firefox на ПК и Firefox для Android.</strong></p> - -<p><strong>Начиная с <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 57</a>, только дополнения разработанные на основе WebExtensions API будут поддерживаться для Firefox на ПК и Firefox для Android. </strong></p> - -<p> Даже до Firefox 57 изменения, появляющиеся на платформе Firefox, нарушат многие устаревшие расширения. Эти изменения включают многопроцессорные Firefox (e10s), песочницу и несколько процессов контента. Устаревшие расширения, на которые влияют эти изменения, должны мигрировать, чтобы использовать API WebExtensions, если они могут. Дополнительную информацию см. в <a href="https://blog.mozilla.org/addons/2017/02/16/the-road-to-firefox-57-compatibility-milestones/">документе "Признаки совместимости"</a>.</p> - -<p>Страница wiki, содержащая <a href="https://wiki.mozilla.org/Add-ons/developer/communication">ресурсы, пути миграции, рабочие часы и т.д.</a>, доступна, чтобы помочь разработчикам перейти на новые технологии.</p> -</div> - -<p> </p> - -<p>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.</p> - -<p>These examples demonstrate how to accomplish basic tasks that might not be immediately obvious.</p> - -<h2 id="General" name="General">General</h2> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/From_articles" title="/en-US/docs/Code_snippets/From_articles">Examples and demos from MDN articles</a></dt> - <dd>A collection of examples and demos from articles.</dd> - <dt><a href="/en-US/docs/Code_snippets/Windows" title="/en-US/docs/Code_snippets/Windows">Window code</a></dt> - <dd>Opening and manipulating windows</dd> - <dt><a href="/en-US/docs/Code_snippets/Toolbar" title="/en-US/docs/Code_snippets/Toolbar">Toolbar</a></dt> - <dd>Toolbar related code</dd> - <dt><a href="/en-US/docs/Code_snippets/Sidebar" title="/en-US/docs/Code_snippets/Sidebar">Sidebar</a></dt> - <dd>Sidebar related code</dd> - <dt><a href="/en-US/docs/Code_snippets/Forms">Forms</a></dt> - <dd>Forms related code</dd> - <dt><a href="/en-US/docs/Code_snippets/XML" title="/en-US/docs/Code_snippets/XML">XML</a></dt> - <dd>Code used to parse, write, manipulate, etc. XML</dd> - <dt><a href="/en-US/docs/Code_snippets/File_I_O" title="/en-US/docs/Code_snippets/File_I/O">File I/O</a></dt> - <dd>Code used to read, write and process files</dd> - <dt><a href="/en-US/docs/Code_snippets/Drag_&_Drop" title="/en-US/docs/Code_snippets/Drag_&_Drop">Drag & Drop</a></dt> - <dd>Code used to setup and handle drag and drop events</dd> - <dt><a href="/en-US/docs/Code_snippets/Dialogs_and_Prompts" title="/en-US/docs/Code_snippets/Dialogs_and_Prompts">Dialogs</a></dt> - <dd>Code used to display and process dialog boxes</dd> - <dt><a href="/en-US/docs/Code_snippets/Alerts_and_Notifications" title="/en-US/docs/Code snippets/Alerts and Notifications">Alerts and Notifications </a></dt> - <dd>Modal and non-modal ways to notify users</dd> - <dt><a href="/en-US/docs/Code_snippets/Preferences" title="/en-US/docs/Code_snippets/Preferences">Preferences</a></dt> - <dd>Code used to read, write, and modify preferences</dd> - <dt><a href="/en-US/docs/Code_snippets/JS_XPCOM" title="/en-US/docs/Code_snippets/JS_XPCOM">JS XPCOM</a></dt> - <dd>Code used to define and call XPCOM components in JavaScript</dd> - <dt><a href="/en-US/docs/Code_snippets/Running_applications" title="/en-US/docs/Code_snippets/Running_applications">Running applications</a></dt> - <dd>Code used to run other applications</dd> - <dt><a href="/en-US/docs/Code_snippets/Canvas" title="/en-US/docs/Code_snippets/Canvas"><code><canvas></code> related</a></dt> - <dd><a href="/en-US/docs/HTML/Canvas" title="/en-US/docs/HTML/Canvas">WHAT WG Canvas</a>-related code</dd> - <dt><a href="/en-US/docs/Signing_a_XPI" title="/en-US/docs/Signing_a_XPI">Signing a XPI</a></dt> - <dd>How to sign an XPI with PKI</dd> - <dt><a href="/en-US/docs/Code_snippets/Threads">Delayed Execution</a></dt> - <dd>Performing background operations.</dd> - <dt><a href="/en-US/docs/Code_snippets/Miscellaneous" title="/en-US/docs/Code_snippets/Miscellaneous">Miscellaneous</a></dt> - <dd>Miscellaneous useful code fragments</dd> - <dt><a href="/en-US/docs/Code_snippets/HTML_to_DOM" title="/en-US/docs/Code_snippets/HTML_to_DOM">HTML to DOM</a></dt> - <dd>Using a hidden browser element to parse HTML to a window's DOM</dd> -</dl> - -<h2 id="javascript-libraries" name="javascript-libraries">JavaScript libraries</h2> - -<p>Here are some JavaScript libraries that may come in handy.</p> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/StringView" title="/en-US/docs/Code_snippets/StringView">StringView</a></dt> - <dd>A library that implements a <code>StringView</code> view for <a href="/en-US/docs/Web/JavaScript/Typed_arrays" title="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a>. This lets you access data in typed arrays using C-like string functions.</dd> - <dt><a href="/en-US/Add-ons/Code_snippets/Rosetta" title="/en-US/docs/Code_snippets/Rosetta">Rosetta</a></dt> - <dd>By default, the only possible standardized scripting language for HTML is <strong>ECMAScript</strong>. 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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed arrays</a> in ECMAScript allow us, in theory, to build full <a class="external external-icon" href="http://en.wikipedia.org/wiki/Virtual_machine">virtual machines</a> 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.</dd> -</dl> - -<h2 id="Browser-oriented_code" name="Browser-oriented_code">Browser-oriented code</h2> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/Tabbed_browser" title="/en-US/docs/Code_snippets/Tabbed_browser">Tabbed browser code</a> (Firefox/SeaMonkey)</dt> - <dd>Basic operations, such as page loading, with the tabbed browser, which is the heart of Mozilla's browser applications</dd> - <dt><a href="/en-US/docs/Code_snippets/Cookies" title="/en-US/docs/Code_snippets/Cookies">Cookies</a></dt> - <dd>Reading, writing, modifying, and removing cookies</dd> - <dt><a href="/en-US/docs/Code_snippets/Page_Loading" title="/en-US/docs/Code_snippets/Page_Loading">Page Loading</a></dt> - <dd>Code used to load pages, reload pages, and listen for page loads</dd> - <dt><a href="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages">Interaction between privileged and non-privileged code</a></dt> - <dd>How to communicate from extensions to websites and vice-versa.</dd> - <dt><a href="/en-US/docs/Code_snippets/Downloading_Files" title="/en-US/docs/Code_snippets/Downloading_Files">Downloading Files</a></dt> - <dd>Code to download files, images, and to monitor download progress</dd> - <dt><a href="/en-US/docs/Code_snippets/Password_Manager" title="/en-US/docs/Code_snippets/Password_Manager">Password Manager</a></dt> - <dd>Code used to read and write passwords to/from the integrated password manager</dd> - <dt><a href="/en-US/docs/Code_snippets/Bookmarks" title="/en-US/docs/Code_snippets/Bookmarks">Bookmarks</a></dt> - <dd>Code used to read and write bookmarks</dd> - <dt><a href="/en-US/docs/Code_snippets/JavaScript_Debugger_Service" title="/en-US/docs/Code_snippets/JavaScript_Debugger_Service">JavaScript Debugger Service</a></dt> - <dd>Code used to interact with the JavaScript Debugger Service</dd> -</dl> - -<h2 id="SVG" name="SVG">SVG</h2> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/SVG_General" title="/en-US/docs/Code_snippets/SVG_General">General</a></dt> - <dd>General information and utilities</dd> - <dt><a href="/en-US/docs/Code_snippets/SVG_Animation" title="/en-US/docs/Code_snippets/SVG_Animation">SVG Animation</a></dt> - <dd>Animate SVG using JavaScript and SMIL</dd> - <dt><a href="/en-US/docs/Code_snippets/SVG_Interacting_with_script" title="/en-US/docs/Code_snippets/SVG_Interacting_with_script">SVG Interacting with Script</a></dt> - <dd>Using JavaScript and DOM events to create interactive SVG</dd> - <dt><a href="/en-US/docs/Code_snippets/Embedding_SVG" title="/en-US/docs/Code_snippets/Embedding_SVG">Embedding SVG in HTML and XUL</a></dt> - <dd>Using SVG to enhance HTML or XUL based markup</dd> -</dl> - -<h2 id="XUL_Widgets" name="XUL_Widgets">XUL Widgets</h2> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/HTML_in_XUL_for_rich_tooltips" title="/en-US/docs/Code_snippets/HTML_in_XUL_for_rich_tooltips">HTML in XUL for Rich Tooltips</a></dt> - <dd>Dynamically embed HTML into a XUL element to attain markup in a tooltip</dd> - <dt><a href="/en-US/docs/Code_snippets/Label_and_description" title="/en-US/docs/Code_snippets/Label_and_description">Label and description</a></dt> - <dd>Special uses and line breaking examples</dd> - <dt><a href="/en-US/docs/Code_snippets/Tree" title="/en-US/docs/Code_snippets/Tree">Tree</a></dt> - <dd>Setup and manipulation of trees using XUL and JS</dd> - <dt><a href="/en-US/docs/Code_snippets/Scrollbar" title="/en-US/docs/Code_snippets/Scrollbar">Scrollbar</a></dt> - <dd>Changing style of scrollbars. Applies to scrollbars in browser and iframe as well.</dd> - <dt><a href="/en-US/docs/Code_snippets/Autocomplete" title="/en-US/docs/Code_snippets/Autocomplete">Autocomplete</a></dt> - <dd>Code used to enable form autocomplete in a browser</dd> - <dt><a href="/en-US/docs/Code_snippets/Boxes" title="/en-US/docs/Code_snippets/Boxes">Boxes</a></dt> - <dd>Tips and tricks when using boxes as containers</dd> - <dt><a class="internal" href="/en-US/docs/Code_snippets/Tabbox" title="/en-US/docs/Code snippets/Tabbox">Tabbox</a></dt> - <dd>Removing and manipulating tabs in a tabbox</dd> -</dl> - -<h2 id="Windows-specific" name="Windows-specific">Windows-specific</h2> - -<dl> - <dt><a href="/en-US/docs/Code_snippets/Finding_Window_Handles" title="/en-US/docs/Code_snippets/Finding_Window_Handles">Finding Window Handles (HWND)</a> (Firefox)</dt> - <dd>How to use Windows API calls to find various kinds of Mozilla window handles. Window handles can be used for IPC and Accessibility purposes.</dd> - <dt><a href="/en-US/docs/Accessing_the_Windows_Registry_Using_XPCOM" title="/en-US/docs/Accessing_the_Windows_Registry_Using_XPCOM">Using the Windows Registry with XPCOM</a></dt> - <dd>How to read, write, modify, delete, enumerate, and watch registry keys and values.</dd> -</dl> - -<h2 id="External_links" name="External_links">External links</h2> - -<p>The content at <a class="external" href="http://kb.mozillazine.org/Category:Example_code">MozillaZine Example Code</a> is slowly being moved here, but you can still find useful examples there for now.</p> diff --git a/files/ru/mozilla/add-ons/code_snippets/куки/index.html b/files/ru/mozilla/add-ons/code_snippets/куки/index.html deleted file mode 100644 index 7a77657bdb..0000000000 --- a/files/ru/mozilla/add-ons/code_snippets/куки/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Cookies -slug: Mozilla/Add-ons/Code_snippets/куки -translation_of: Archive/Add-ons/Code_snippets/Cookies ---- -<h3 id="Reading_existing_cookies" name="Reading_existing_cookies">Чтение существующих cookie</h3> - -<p>Cookie для данного хоста, как объекты <code><a href="https://developer.mozilla.org/ru/docs/Mozilla/Add-ons/Code_snippets/%D0%BA%D1%83%D0%BA%D0%B8" title="">nsICookie2</a></code>, могут быть пронумерированны так:</p> - -<pre class="brush: js">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"); -} -</pre> - -<p>Все cookie, вне зависимости от хоста, могут быть пронумерированны с помощью <code>Services.cookies.enumerator</code>, а не <code>getCookiesFromHost()</code>.</p> - -<h3 id="Setting_a_cookie" name="Setting_a_cookie">Настраивание cookie</h3> - -<p>Следующий код показывает как настроить cookie в Firefox.</p> - -<pre class="brush: js">Services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date); -</pre> - -<h3 id="See_also" name="See_also">Смотрите также</h3> - -<ul> - <li>{{ Domxref("document.cookie") }}</li> - <li>{{ Interface("nsICookie") }}</li> - <li>{{ Interface("nsICookie2") }}</li> - <li>{{ Interface("nsICookieService") }}</li> - <li>{{ Interface("nsICookieManager") }}</li> - <li>{{ Interface("nsICookieManager2") }}</li> - <li><a href="/en/Web_Development/HTTP_cookies" title="HTTP cookies">HTTP cookies</a></li> -</ul> diff --git a/files/ru/mozilla/add-ons/firefox_for_android/index.html b/files/ru/mozilla/add-ons/firefox_for_android/index.html deleted file mode 100644 index a636438acb..0000000000 --- a/files/ru/mozilla/add-ons/firefox_for_android/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Устаревшие расширения для Firefox для Android -slug: Mozilla/Add-ons/Firefox_for_Android -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Legacy_Firefox_for_Android ---- -<p>Firefox для Android поддерживает надстройки, используя ту же <a href="/ru/Add-ons" title="ru/Extensions">систему расширения</a>, что и все другие приложения на базе Gecko. Вы можете использовать <a href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/mobile.html">SDK Add-on</a> или создать <a href="/en-US/Add-ons/Bootstrapped_extensions">вручную bootstrap-дополнения</a>. Вы даже можете создавать традиционные перезагружаемые дополнения, хотя предпочтительны и другие два подхода.</p> - -<p>Дополнения, которые работают с настольным Firefox, <strong>не</strong> работают автоматически в Firefox для Android:</p> - -<ul> - <li>В пользовательском интерфейсе нет видимого XUL, поэтому вы не можете использовать наложение для создания пользовательского интерфейса.</li> - <li>Внутренний код и объекты, такие как <code>gBrowser</code>, не существуют. Посмотрите на Firefox в файле <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/mobile/android/chrome/content/browser.js" title="http://mxr.mozilla.org/mozilla-central/source/mobile/android/chrome/content/browser.js"><code>browser.js </code></a>Android, чтобы узнать о внутренних компонентах. Значительная часть той же фундаментальной функциональности существует.</li> - <li>Службы, такие как <code>nsIPromptService</code> и <code>nsIAlertsService</code>, реализованы для использования собственного пользовательского интерфейса Android.</li> - <li>Существует простой объект JavaScript, называемый <a href="https://developer.mozilla.org/en/Extensions/Mobile/API/NativeWindow" title="en/Extensions/Mobile/NativeWindow"><code>NativeWindow</code></a>, который позволяет вам манипулировать частями пользовательского интерфейса Android.</li> -</ul> - -<p>Следующие статьи предоставляют помощь в разработке расширений для Firefox на Android. Кроме того, обратитесь к <a class="internal" href="/en-US/Add-ons" title="En/Extensions">общей документации по расширениям</a>, которая применяется ко всем приложениям Mozilla</p> - -<div class="column-container"> -<div class="column-half"> -<h3 id="Учебники">Учебники</h3> - -<dl> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/Walkthrough">Прохождение</a></dt> - <dd>Разработка, упаковка и установка простого дополнения для Firefox для Android.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/Firefox_Hub_Walkthrough">Прохождение Firefox Hub</a></dt> - <dd>Как разработать Firefox Hub add-on и добавить его в Firefox для Android (главная страница).</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Mobile_development">Add-on SDK</a></dt> - <dd>Как разрабатывать дополнения Firefox для Android с помощью Add-on SDK.</dd> -</dl> - -<h3 id="Образец_кода">Образец кода</h3> - -<dl> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/Code_snippets">Фрагменты кода</a></dt> - <dd>Образцы кода для общих задач.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/Initialization_and_Cleanup">Инициализация и очистка</a></dt> - <dd>Как инициализировать ваше дополнение при его запуске и очистке при его закрытии.</dd> - <dt><a href="https://github.com/mozilla/firefox-for-android-addons">Firefox для Android Add-ons в репозитории Github</a></dt> - <dd>Коллекция модулей JS, кода примера и плагинов-репозиториев, которые помогут вам создавать надстройки для Firefox для Android.</dd> -</dl> -</div> - -<div class="column-half"> -<h3 id="Справка_по_API">Справка по API</h3> - -<dl> - <dt><a class="internal" href="/en-US/Add-ons/Firefox_for_Android/API/NativeWindow"><code>NativeWindow</code></a></dt> - <dd>Создайте собственные виджеты пользовательского интерфейса Android.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/API/BrowserApp"><code>BrowserApp</code></a></dt> - <dd>Доступ к вкладкам браузера и веб-содержимому, которое они размещают.</dd> - <dt><a class="internal" href="/en-US/Add-ons/Firefox_for_Android/API/Prompt.jsm"><code>Prompt.jsm</code></a></dt> - <dd>Вывод встроенного диалогового окна Android.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/API/HelperApps.jsm"><code>HelperApps.jsm</code></a></dt> - <dd>Запросить и запустить собственные приложения, установленные в системе.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/API/Notifications.jsm"><code>Notifications.jsm</code></a></dt> - <dd>Использование внешних свойств уведомлений системы Android.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/API/Home.jsm"><code>Home.jsm</code></a></dt> - <dd>Настройка домашней страницы.</dd> - <dt><a href="/en-US/Add-ons/Firefox_for_Android/API/HomeProvider.jsm"><code>HomeProvider.jsm</code></a></dt> - <dd>Сохранять данные для отображения на главной странице.</dd> - <dt> </dt> -</dl> -</div> -</div> - -<p><code> </code></p> - -<div> -<div id="tap-translate"> </div> -</div> - -<div> -<div id="tap-translate"> </div> -</div> - -<div> -<div id="tap-translate"> </div> -</div> diff --git a/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html b/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html deleted file mode 100644 index ae42b11ad1..0000000000 --- a/files/ru/mozilla/add-ons/how_to_convert_an_overlay_extension_to_restartless/index.html +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: How to convert an overlay extension to restartless -slug: Mozilla/Add-ons/How_to_convert_an_overlay_extension_to_restartless -translation_of: Archive/Add-ons/How_to_convert_an_overlay_extension_to_restartless ---- -<div class="note"> -<p>This article is a step-by-step tutorial on how to convert an old <a href="https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions">overlay-based extension</a> into a <a href="https://developer.mozilla.org/en-US/Add-ons/Bootstrapped_extensions">restartless (bootstrapped) extension</a> that is also extractionless.</p> -</div> - -<h2 id="Requirements">Requirements</h2> - -<p>First off, what kind of <a href="https://developer.mozilla.org/en-US/Add-ons">add-on</a> are we talking about here? Well, <a href="https://developer.mozilla.org/en-US/docs/XUL_Overlays">XUL overlays</a> and windows, <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules">JSM files</a>, <a href="https://developer.mozilla.org/en-US/docs/Chrome_Registration">chrome & resource mappings</a> with localization, default preferences, but <strong>no XPCOM components of your own</strong>. Some of that will have to be replaced and the rest will need to be loaded differently.</p> - -<p>Next, what's the minimum version of Firefox we should require (preferably an <a href="https://www.mozilla.org/firefox/organizations/">ESR</a>)? This guide targets <strong>Firefox 17 ESR or later</strong> (or anything else Gecko 17+, such as SeaMonkey 2.14+). This is<em>two</em> 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.</p> - -<p>There will be no usage of the <a href="/en-US/Add-ons/SDK">Add-on SDK</a> or any other external libraries here. Everything will use APIs available in Firefox 17+ or code provided here.</p> - -<h2 id="Step_1_Use_Services.jsm">Step 1: Use Services.jsm</h2> - -<p>If you load one of Mozilla's internal <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules">JSM files</a>, for example <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm">Services.jsm</a>, you'll do so via privileged JavaScript code like this:</p> - -<pre class="brush: js">Components.utils.import("resource://gre/modules/Services.jsm");</pre> - -<p>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 <a href="https://developer.mozilla.org/en-US/docs/Chrome_Registration">chrome.manifest</a> to add and remove resource, chrome, locale, & etc. mappings, so that you can access your files with custom paths such as:</p> - -<pre>resource://myAddon/filename.ext -chrome://myAddon/content/filename.ext</pre> - -<h2 id="Step_2_No_more_resource_URIs_for_files_internal_to_your_bundle">Step 2: No more resource:// URIs for files internal to your <a href="/en-US/docs/Bundles">bundle</a></h2> - -<p>Unfortunately, resource mappings in your chrome.manifest are <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=675372">still not usable</a> 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 "<a href="https://developer.mozilla.org/en-US/docs/Components.utils.import">Components.utils.import()</a>" 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 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=903959">bleeds into content</a> 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).</p> - -<h3 id="Step_2a_Load_your_JSM_from_chrome">Step 2a: Load your JSM from chrome://</h3> - -<p>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 <a href="https://developer.mozilla.org/en-US/docs/Chrome_Registration#content">chrome mapping</a> 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.</p> - -<p>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.</p> - -<h3 id="Step_2b_Audit_any_remaining_resource_URI_usage_internal_to_your_extension">Step 2b: Audit any remaining resource:// URI usage internal to your extension</h3> - -<p>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 <a href="https://developer.mozilla.org/en-US/Add-ons/Bootstrapped_extensions#Bootstrap_data">URI for their install location</a> on startup, so you should look into what you can do with that.</p> - -<h2 id="Step_3_No_more_nsIFile_access_for_files_internal_to_your_bundle">Step 3: No more <a href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIFile">nsIFile</a> access for files internal to your bundle</h2> - -<p>For an extractionless extension, access to files internal to your bundle will not be possible using the nsIFile interface.</p> - -<p>If you need to read data, or otherwise access files within your bundle, there are two options. The first is to use the <a href="/en-US/docs/XPCOM_Interface_Reference/nsIZipReader">nsIZipReader</a> interface which permits continuing to use <a href="/en-US/docs/XPCOM_Interface_Reference/nsIInputStream">nsIInputStream</a>s, etc. The second is to re-code to use <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a>.</p> - -<p>A file:// URI to the install location, or .xpi file, is available in <code>installPath</code> property of the <a href="https://developer.mozilla.org/en-US/Add-ons/Bootstrapped_extensions#Bootstrap_data">bootstrap data structure</a> passed to the <code>startup()</code>, <code>shutdown()</code>, <code>install()</code>, and <code>uninstall()</code> functions in what will be your bootstrap.js file <em>(see below)</em>.</p> - -<p>How to get and load the data of of your add-on's files using the <a href="https://developer.mozilla.org/en-US/Add-ons/Add-on_Manager/AddonManager">Add-on Manager API</a>:</p> - -<pre class="brush: js">// 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 */ -});</pre> - -<p>This bit of code is paraphrased and probably not to be recommended as-is, but it should work. (note that the usage of an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Integers">octal integer literal</a>, while standard for handling permissions, is dangerous and deprecated; usage of use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode#Converting_mistakes_into_errors">ES5 strict mode</a> to disable this and other foot-guns is recommended) If you need to read/manipulate binary data, a <a href="/en-US/docs/XPCOM_Interface_Reference/nsIBinaryInputStream">nsIBinaryInputStream</a> instance is what you'll use on that stream (e.g. 32-bit integers, or fun stuff like <a href="https://flagfox.wordpress.com/2011/02/12/apparently-javascript-cant-do-64-bit-math/">48-bit integers</a>). 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).</p> - -<h3 id="Step_3a_Option_1_Use_nsIZipReader">Step 3a: Option 1: Use <a href="/en-US/docs/XPCOM_Interface_Reference/nsIZipReader">nsIZipReader</a></h3> - -<pre class="brush: js">let zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"] - .createInstance(Components.interfaces.nsIZipReader); -zipReader.open(addonData.installPath); -... -</pre> - -<p>From there you can open <a href="/en-US/docs/XPCOM_Interface_Reference/nsIInputStream">nsIInputStream</a>s, 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.</p> - -<h3 id="Step_3b_Option_2_Use_XMLHttpRequest">Step 3b: Option 2: Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></h3> - -<p>Now, how do we replace that? The answer to that question is to <strong>load your file from a chrome:// URI using XMLHttpRequest</strong>. You may now have another question: wait, what does this have to do with <a href="/en-US/docs/XML">XML</a> or <a href="/en-US/docs/Web/HTTP">HTTP</a>? The answer to that question is, of course, <em>nothing</em>. <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> 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:</p> - -<pre class="brush: js">const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", - "nsIXMLHttpRequest");</pre> - -<p>Here's how to load a file using it:</p> - -<pre class="brush: js">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 */ -});</pre> - -<p>Note: When using XMLHttpRequest to access a file:// URL the <code>request.status</code> is not properly set to <code>200</code> to indicate success. In such cases, <code>request.readyState == 4</code>, <code>request.status == 0</code> and <code>request.response</code> will evaluate to true.</p> - -<p>If your file is text, use "text" as your data type. If you're getting <a href="https://developer.mozilla.org/en-US/docs/JSON">JSON</a> 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. <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties">MDN says</a> you can set the type to "json" instead, if you prefer to have it parse things for you.</p> - -<p>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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a>. 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. <strong>The basic typed array views are not endian-safe.</strong> 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 <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a>, but no, it doesn't. Don't use any of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView#Typed_array_subclasses">basic typed arrays</a> 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).</p> - -<p>The solution to read arbitrary binary data, of various sizes, in an endian-safe way, is to use <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataView">DataView</a>. 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.</p> - -<p>Reportedly <a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Using_XMLHttpRequest_from_JavaScript_modules_.2F_XPCOM_components">XMLHttpRequest doesn't work reliably when used in JSM under versions of Firefox less than 16</a>, however as previously mentioned, this guide should be taken as requiring Firefox 17+.</p> - -<h2 id="Step_4_Manually_handle_default_preferences">Step 4: Manually handle default preferences</h2> - -<p>Normal extensions load <a href="https://developer.mozilla.org/en-US/docs/Default_Preferences">default preferences</a> from a standardized file automatically. Restartless extensions <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=564675">don't</a> (for no good reason). This part is fairly easy to implement yourself, at least. Here are some functions to handle this:</p> - -<pre class="brush: js">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); -}</pre> - -<p>Just grab the above, move your default preferences file to your chrome mapping, and then do the following line once during your startup:</p> - -<pre class="brush: js">Services.scriptloader.loadSubScript("chrome://myAddon/content/defaultprefs.js", - {pref:setDefaultPref} ); -</pre> - -<p>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.</p> - -<h3 id="Step_4a_Another_way_to_handle_default_preferences">Step 4a: Another way to handle default preferences</h3> - -<p>If you want to keep your preference file in <strong>defaults/preferences/</strong>, 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 <a href="https://github.com/firebug/firebug/blob/master/extension/modules/prefLoader.js">prefLoader.js</a> or load this <a href="https://gist.github.com/oshybystyi/8cf882bc8b0c9a95a116">workaround module</a>.</p> - -<h2 id="Step_5_No_more_internal_JAR_files">Step 5: No more internal JAR files</h2> - -<p>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:</p> - -<pre>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)</pre> - -<p>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 <a href="https://developer.mozilla.org/en-US/Add-ons/Install_Manifests">install.rdf</a>.</p> - -<p>Why the internal JAR? Well, two reasons:</p> - -<ol> - <li>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.</li> - <li>XPI files are glorified ZIPs, and ZIP compression is horrible. Doing an<em>uncompressed</em> internal JAR (aka, another ZIP) acts like a poor-man's <a href="https://en.wikipedia.org/wiki/Solid_archive">solid archive</a> and significantly boosts the overall compression ratio of the XPI, resulting in smaller installers and updates.</li> -</ol> - -<p>So, it's pretty much internal JAR<em>or</em> extractionless XPI. Well, <strong>you can't use an internal JAR anymore</strong>. 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 <a href="https://developer.mozilla.org/en-US/Add-ons/Install_Manifests#unpack">here</a> for the list of stuff you can't have in addition to no resource:// URIs or file:// URIs to files inside your XPI.</p> - -<p>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.</p> - -<h2 id="Step_6_No_more_XUL_overlays">Step 6: No more XUL overlays</h2> - -<p>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 <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.loadOverlay">dynamically loading</a> and unloading your overlay, however dynamically manipulating the DOM of your XUL window is usually the more straightforward route.</p> - -<p>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: <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById">document.getElementByID()</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.createElement">document.createElement()</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/element">Element reference</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">Node reference</a> (DOM elements are also nodes).</p> - -<p>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.</p> - -<h3 id="Step_6a._Details_on_adding_elements_dynamically_to_chrome_XUL_window">Step 6a. Details on adding elements dynamically to chrome XUL window</h3> - -<p>There is a way that makes constructing of UI a lot similar to the way it was made with XUL overlay. It involves using <a href="https://github.com/firebug/firebug.sdk/blob/master/lib/core/xul.js">firebug.sdk</a>. The next is example of the code:</p> - -<pre class="brush: js">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'}) - ... -</pre> - -<p>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 <a href="https://github.com/oshybystyi/FireX-Pixel-Perfect/blob/issue-5-make-addon-restartless/content/ui.jsm#L94">here</a>. It involves using of firebug.sdk xul.js with <a href="https://github.com/oshybystyi/FireX-Pixel-Perfect/blob/issue-5-make-addon-restartless/content/lib/xul.js">few modifications</a>.</p> - -<h2 id="Step_7_Manually_handle_global_CSS_Stylesheets">Step 7: Manually handle global CSS Stylesheets</h2> - -<p>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.</p> - -<pre class="brush: js">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.<code>AUTHOR_SHEET</code>); - } -... -} - -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.<code>AUTHOR_SHEET</code>)) { - styleSheetService.unregisterSheet(styleSheetURI, styleSheetService.<code>AUTHOR_SHEET</code>); - } - } -... -</pre> - -<h2 id="Step_8_Window_icons">Step 8: Window icons</h2> - -<p>Firefox does not scan the <code>chrome/icons/default</code> directory of restartless or extrationless extensions for <a href="/en-US/docs/Window_icons">window icons</a>. If you are using custom window icons, they will need to be moved to <code>%MozDir%/icons/default/</code> 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 <code>unload()</code> 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).</p> - -<h2 id="Step_9_bootstrap.js">Step 9: bootstrap.js</h2> - -<p>A <a href="/en-US/docs/Extensions/bootstrap.js">bootstrap.js</a> file in the root of your XPI, next to your chrome.manifest and install.rdf, will be the <a href="https://developer.mozilla.org/en-US/Add-ons/Bootstrapped_extensions#Bootstrap_entry_points">heart</a> of your restartless add-on. Think of it as main.c, but for JavaScript based Firefox restartless add-ons. A basic bootstrap.js file:</p> - -<pre class="brush: js">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) { } -}; -</pre> - -<p>As mentioned above, <a href="https://developer.mozilla.org/en-US/docs/Components.utils.unload">Components.utils.unload()</a> 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.</p> - -<p>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 <code>unloadFromWindow()</code> something like this:</p> - -<pre class="brush: js">function unloadFromWindow(window) -{ - var event = window.document.createEvent("Event"); - event.initEvent("myAddonName-unload",false,false); - window.dispatchEvent(event); -} -</pre> - -<p>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.</p> - -<h2 id="Step_10_Bypass_cache_when_loading_properties_files">Step 10: Bypass cache when loading properties files</h2> - -<p>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 can<em>sometimes</em> produce this error. It's not reliably reproducible, but it does happen.<em>Yes, this is a pain in the ass.</em></p> - -<p>The suggestion that seems to work is to use a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=719376#c0">hack</a> to bypass the string bundle cache. You should still be caching a reference to your string bundle on add-on startup, preferably using <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter%28%29">XPCOMUtils.jsm</a> to lazily load the file. For example:</p> - -<pre class="brush: js">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()); -} -</pre> - -<p>Just do <code>strings.GetStringFromName(stringID)</code> as you normally would. The <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter%28%29">lazy getter magic</a> 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 <em>should</em> still be cleared.</p> - -<h2 id="Put_it_all_together">Put it all together</h2> - -<p>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 <code>bootstrap.js:startup()</code> rather than a "load" handler in a XUL overlay.</p> - -<p>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.</p> - -<p><strong>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.</strong></p> - -<p>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 to<em>uninstall</em> that first.</p> - -<div class="note"> -<p>This tutorial was originally written by Dave Garrett from his experience <a href="https://flagfox.wordpress.com/2014/01/19/writing-restartless-addons/">porting the Flagfox extension</a>.</p> -</div> - -<h2 id="Further_reading">Further reading</h2> - -<ul> - <li>Author <a href="https://flagfox.wordpress.com/2014/01/19/writing-restartless-addons/">original article.</a></li> - <li>Another real-world example of porting overlay-based extension into restartless (<a href="https://github.com/oshybystyi/FireX-Pixel-Perfect/compare/v1.4...oshybystyi:issue-5-make-addon-restartless">git diff</a>).</li> - <li>Another <a href="https://github.com/firebug/pixel-perfect/blob/master/lib/pixel-perfect-popup.js#L197">example</a> of using firebug.sdk xul.js to construct ui.</li> -</ul> diff --git a/files/ru/mozilla/add-ons/overlay_extensions/index.html b/files/ru/mozilla/add-ons/overlay_extensions/index.html deleted file mode 100644 index ceac592b8d..0000000000 --- a/files/ru/mozilla/add-ons/overlay_extensions/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Overlay extensions -slug: Mozilla/Add-ons/Overlay_Extensions -tags: - - Add-ons - - Extensions - - Landing - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Overlay_Extensions ---- -<p>Эта страница содержит ссылки на документы с описанием подхода к разработке расширений для приложений, работающих на движке Gecko, которые используют:</p> - -<ul> - <li>описание интерфейса на основе "XUL overlays"</li> - <li>API-интерфейсы, доступные <a href="/ru/docs/Словарь/privileged_code">привилегированному коду</a>, например модулям <a href="/en-US/docs/XUL/tabbrowser"><code>tabbrowser</code></a> и <a href="/en-US/docs/Mozilla/JavaScript_code_modules">JavaScript</a> для взаимодействия с приложениями и контентом.</li> -</ul> - -<p>До релиза Firefox 4 и до движка Gecko 2.0 это был единственный способ разработки расширений. Эта методология разработки была заменена на следующие две:<a href="/ru/Add-ons/загрузочные_расширения"> расширения, не требующие перезапуска</a>, и расширения на основе <a href="/ru/Add-ons/SDK">Add-on SDK</a>. Они обе построены поверх первой. <a href="/ru/docs/Словарь/privileged_code">Привилегированные интерфейсы</a> JavaScript API, описанные здесь могут быть также использованы в новых техниках разработки дополнений.</p> - -<h2 id="Школа_XUL">Школа XUL</h2> - -<p><a href="/ru/docs/XUL_School">Школа XUL</a> - это комплексный учебник по разработке дополнений, сфокусированный на разработке расширений для Firefox, но также подходящий для других приложений, основанных на движке Gecko.</p> - -<h2 id="Ресурсы">Ресурсы</h2> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Mozilla/Add-ons/Setting_up_extension_development_environment">Настройка среды</a></dt> - <dd>Настройка приложений для разработки расширений.</dd> - <dt><a href="/ru/docs/XUL">XUL</a></dt> - <dd>Учебники и справочники по языку программирования, используемому XUL-расширениями.</dd> - <dt><a href="/en-US/Mozilla/Add-ons/Code_snippets">Примеры кода</a></dt> - <dd>Примеры кода, которые пригодятся.</dd> - <dt><a href="/en-US/Mozilla/Add-ons/Installing_extensions">Установка расширений</a></dt> - <dd>Как установить расширение копированием файлов в установочный каталог.</dd> - <dt><a href="/en-US/Add-ons/Overlay_extensions/Firefox_addons_developer_guide">Руководство разработчика дополнений для Firefox</a></dt> - <dd>Руководство по разработка расширений.</dd> - <dt><a href="/en-US/docs/Mozilla/JavaScript_code_modules">JavaScript-модули, доступные разработчику</a></dt> - <dd>JavaScript-модули доступные разработчику расширений.</dd> - <dt><a href="/en-US/Mozilla/Add-ons/Inline_Options">Настройка расширения</a></dt> -</dl> -</div> - -<div class="column-half"> -<dl> - <dd>Как добавить свойства расширения, которые появятся в менеджере дополнений (Add-ons Manager).</dd> - <dt><a href="/ru/docs/FAQ_по_расширениям">FAQ</a></dt> - <dd>Решение некоторых общих проблем.</dd> - <dt><a href="/en-US/Mozilla/Add-ons/Extension_Packaging">Сборка и установка расширения</a></dt> - <dd>Сборка и установка.</dd> - <dt><a href="/en-US/Mozilla/Add-ons/Creating_Custom_Firefox_Extensions_with_the_Mozilla_Build_System">Создание бинарных расширений для Firefox</a></dt> - <dd>Создание бинарных расширений.</dd> - <dt><a href="/ru/docs/Building_an_Extension">Создание расширения</a></dt> - <dd>Ещё один небольшой самоучитель по созданию расширения (только на русском языке)</dd> - <dt><a href="/ru/docs/Динамически_изменяемый_пользовательский_интерфейс_на_XUL">Динамически изменяемый пользовательский интерфейс на XUL</a></dt> - <dd>В этой статье обсуждается управление <a href="https://developer.mozilla.org/ru/XUL" title="ru/XUL">XUL</a> интерфейсами с использованием <a href="https://developer.mozilla.org/ru/DOM" title="ru/DOM">DOM</a> и других API.</dd> - <dt><a href="/ru/docs/Настройка_среды_разработки_расширений">Настройка среды разработки расширений</a></dt> - <dd>В этой статье приводится несколько советов о том, как настроить ваше приложение Mozilla для удобной работы над расширениями.</dd> - <dt><a href="/ru/docs/Руководство_по_XUL">Руководство по XUL</a></dt> - <dd>Руководство по XUL</dd> -</dl> -</div> -</div> diff --git a/files/ru/mozilla/add-ons/sdk/guides/index.html b/files/ru/mozilla/add-ons/sdk/guides/index.html deleted file mode 100644 index 1eacaad55a..0000000000 --- a/files/ru/mozilla/add-ons/sdk/guides/index.html +++ /dev/null @@ -1,365 +0,0 @@ ---- -title: Guides -slug: Mozilla/Add-ons/SDK/Guides -tags: - - Add-on SDK -translation_of: Archive/Add-ons/Add-on_SDK/Guides ---- -<p> </p> - -<div class="warning"> -<p>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.</p> - -<p>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 <a href="/en-US/Add-ons/WebExtensions">WebExtensions</a> instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.</p> - -<p><strong>Starting from <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 53</a>, no new legacy add-ons will be accepted on addons.mozilla.org (AMO) for desktop Firefox and Firefox for Android.</strong></p> - -<p><strong>Starting from <a href="https://wiki.mozilla.org/RapidRelease/Calendar">Firefox 57</a>, only extensions developed using WebExtensions APIs will be supported on Desktop Firefox and Firefox for Android. </strong></p> - -<p>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 <a href="https://blog.mozilla.org/addons/2017/02/16/the-road-to-firefox-57-compatibility-milestones/">"Compatibility Milestones" document</a> for more information.</p> - -<p>A wiki page containing <a href="https://wiki.mozilla.org/Add-ons/developer/communication">resources, migration paths, office hours, and more</a>, is available to help developers transition to the new technologies.</p> -</div> - -<section class="Quick_links" id="Quick_Links"> -<ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions"><strong>Browser extensions</strong></a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Getting_started">Getting started</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions">What are extensions?</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension">Your first extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension">Your second extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension">Anatomy of an extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples">Example extensions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next_">What next?</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Concepts">Concepts</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Using_the_JavaScript_APIs">Using the JavaScript APIs</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">Content scripts</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">Match patterns</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files">Working with files</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization">Internationalization</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Security_best_practices">Security best practices</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">Content Security Policy</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging">Native messaging</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#User_Interface">User interface</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface">User Interface</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action">Toolbar button</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions">Address bar button</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars">Sidebars</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items">Context menu items</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages">Options page</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages">Extension pages</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications">Notifications</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox">Address bar suggestions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels">Developer tools panels</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#How_to">How to</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests">Intercept HTTP requests</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page">Modify a web page</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page">Insert external content</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar">Add a button to the toolbar</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page">Implement a settings page</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API">Work with the Tabs API</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Bookmarks_API">Work with the Bookmarks API</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API">Work with the Cookies API</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities">Work with contextual identities</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Porting">Porting</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension">Porting a Google Chrome extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on">Porting a legacy Firefox extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Embedded_WebExtensions">Embedded WebExtensions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_the_Add-on_SDK">Comparison with the Add-on SDK</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_XUL_XPCOM_extensions">Comparison with XUL/XPCOM extensions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities">Chrome incompatibilities</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Differences_between_desktop_and_Android">Differences between desktop and Android</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions#Firefox_workflow">Firefox workflow</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/User_experience_best_practices">User Experience</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">Temporary Installation in Firefox</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging">Debugging</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Testing_persistent_and_restart_features">Testing persistent and restart features</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Developing_WebExtensions_for_Firefox_for_Android">Developing for Firefox for Android</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext">Getting started with web-ext</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/web-ext_command_reference">web-ext command reference</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID">Extensions and the Add-on ID</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Request_the_right_permissions">Request the right permissions</a></li> - </ol> - </li> - <li data-default-state="closed"><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API">JavaScript APIs</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs">Browser support for JavaScript APIs</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms">alarms</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks">bookmarks</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction">browserAction</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserSettings">browserSettings</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browsingData">browsingData</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/clipboard">clipboard</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/commands">commands</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contentScripts">contentScripts</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contextualIdentities">contextualIdentities</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies">cookies</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.inspectedWindow">devtools.inspectedWindow</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.network">devtools.network</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/devtools.panels">devtools.panels</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns">dns</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads">downloads</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events">events</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extension">extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extensionTypes">extensionTypes</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/find">find</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history">history</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n">i18n</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/identity">identity</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/idle">idle</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/management">management</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus">menus</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications">notifications</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/omnibox">omnibox</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction">pageAction</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions">permissions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pkcs11">pkcs11</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/privacy">privacy</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy">proxy</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime">runtime</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/search">search</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/sessions">sessions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/sidebarAction">sidebarAction</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage">storage</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs">tabs</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/theme">theme</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/topSites">topSites</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/types">types</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation">webNavigation</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest">webRequest</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows">windows</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">Manifest keys</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications">applications</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/author">author</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background">background</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_settings_overrides">chrome_settings_overrides</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides">chrome_url_overrides</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands">commands</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts">content_scripts</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy">content_security_policy</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/default_locale">default_locale</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description">description</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/developer">developer</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page">devtools_page</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url">homepage_url</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons">icons</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/incognito">incognito</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version">manifest_version</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name">name</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/omnibox">omnibox</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions">optional_permissions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui">options_ui</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action">page_action</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permissions</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers">protocol_handlers</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/short_name">short_name</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action">sidebar_action</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/theme">theme</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version">version</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version_name">version_name</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources">web_accessible_resources</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes"><strong>Themes</strong></a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Theme_concepts">Browser themes</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Theme_concepts">Browser theme concepts</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_themes">Lightweight themes</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_themes">Lightweight themes</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Themes/Lightweight_Themes/FAQ">Lightweight themes FAQ</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution"><strong>Publishing and Distribution</strong></a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution">Publishing add-ons</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution">Signing and distribution overview</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Package_your_extension_">Package your extension</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Submitting_an_add-on">Submit an add-on</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Source_Code_Submission">Source code submission</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Resources_for_publishers">Resources for publishers</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Listing">Creating an appealing listing</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Reviews">Review policies</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Agreement">Developer agreement</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/AMO/Policy/Featured">Featured add-ons</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/Distribution/Retiring_your_extension">Retiring your extension</a></li> - </ol> - </li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options">Distributing add-ons</a> - <ol> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Sideloading_add-ons">For sideloading</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Add-ons_for_desktop_apps">For desktop apps</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Alternative_distribution_options/Add-ons_in_the_enterprise">For an enterprise</a></li> - </ol> - </li> - <li><a href="https://discourse.mozilla.org/c/add-ons"><strong>Community and Support</strong></a></li> - <li><a href="#">Channels</a> - <ol> - <li><a href="https://blog.mozilla.org/addons">Add-ons blog</a></li> - <li><a href="https://discourse.mozilla.org/c/add-ons">Add-on forums</a></li> - <li><a href="http://stackoverflow.com/questions/tagged/firefox-addon">Stack Overflow</a></li> - <li><a href="/en-US/docs/Mozilla/Add-ons/#Contact_us">Contact us</a></li> - </ol> - </li> -</ol> -</section> - -<p> </p> - -<p>This page lists more theoretical in-depth articles about the SDK.</p> - -<hr> -<h3 id="Contributor's_guide"><a name="contributors-guide">Contributor's guide</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="Guides/Getting_Started">Getting Started</a></dt> - <dd>Learn how to contribute to the SDK: getting the code, opening/taking a bug, filing a patch, getting reviews, and getting help.</dd> - <dt><a href="Guides/Modules">Modules</a></dt> - <dd>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.</dd> - <dt><a href="Guides/Classes_and_Inheritance">Classes and Inheritance</a></dt> - <dd>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.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="Guides/Private_Properties">Private Properties</a></dt> - <dd>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).</dd> - <dt><a href="Guides/Content_Processes">Content Processes</a></dt> - <dd>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.</dd> - <dt><a href="Guides/Testing_the_Add-on_SDK">Testing the Add-on SDK</a></dt> - <dd>Learn how to run the Add-on SDK test suites.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="SDK_infrastructure"><a name="sdk-infrastructure">SDK infrastructure</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="Guides/Module_structure_of_the_SDK">Module structure of the SDK</a></dt> - <dd>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.</dd> - <dt><a href="Guides/SDK_API_Lifecycle">SDK API lifecycle</a></dt> - <dd>Definition of the lifecycle for the SDK's APIs, including the stability ratings for APIs.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="Guides/Program_ID">Program ID</a></dt> - <dd>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.</dd> - <dt><a href="Guides/Firefox_Compatibility">Firefox compatibility</a></dt> - <dd>Working out which Firefox releases a given SDK release is compatible with, and dealing with compatibility problems.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="SDK_idioms"><a name="sdk-idioms">SDK idioms</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="Guides/Working_with_Events">Working With Events</a></dt> - <dd>Write event-driven code using the the SDK's event emitting framework.</dd> - <dt><a href="Guides/Content_Scripts">Content scripts guide</a></dt> - <dd>An overview of content scripts, including: what they are, what they can do, how to load them, how to communicate with them.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="Guides/Two_Types_of_Scripts">Two Types of Scripts</a></dt> - <dd>This article explains the differences between the APIs available to your main add-on code and those available to content scripts.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="XUL_migration"><a name="xul-migration">XUL migration</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="Guides/XUL_Migration_Guide">XUL Migration Guide</a></dt> - <dd>Techniques to help port a XUL add-on to the SDK.</dd> - <dt><a href="Guides/XUL_vs_SDK">XUL versus the SDK</a></dt> - <dd>A comparison of the strengths and weaknesses of the SDK, compared to traditional XUL-based add-ons.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="Guides/Porting_the_Library_Detector">Porting Example</a></dt> - <dd>A walkthrough of porting a relatively simple XUL-based add-on to the SDK.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Multiprocess_Firefox"><a name="multiprocess-firefox">Multiprocess Firefox</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="Guides/Multiprocess_Firefox_and_the_SDK">Multiprocess Firefox and the SDK</a></dt> - <dd>How to check whether your add-on is compatible with multiprocess Firefox, and fix it if it isn't.</dd> -</dl> -</div> - -<div class="column-half"> </div> -</div> - -<hr> -<div> -<div class="overheadIndicator communitybox" dir="ltr"> -<div class="column-container"> -<h2 id="Join_the_Add-on_SDK_community">Join the Add-on SDK community</h2> - -<div class="column-half"> -<div class="communitysubhead">Choose your preferred method for joining the discussion:</div> - -<ul class="communitymailinglist"> - <li><a href="https://lists.mozilla.org/listinfo/">Mailing list</a></li> - <li><a href="https://twitter.com/mozillajetpack">Twitter</a></li> - <li><a href="http://stackoverflow.com/questions/tagged/firefox-addon-sdk">Stack Overflow</a></li> - <li><a href="http://groups.google.com/group/mozilla-labs-jetpack">Newsgroup</a></li> - <li><a href="http://groups.google.com/group/mozilla-labs-jetpack/feeds">RSS feed</a></li> -</ul> -</div> - -<div class="column-half"> -<ul class="communitycontact"> - <li><strong>IRC: </strong><a href="irc://irc.mozilla.org/jetpack">#jetpack</a> <span class="smaller">(<a href="https://wiki.mozilla.org/IRC">learn more</a>)</span></li> - <li><strong>Team info: </strong><a href="https://wiki.mozilla.org/Jetpack" title="Designs and plans for the SDK tools">Jetpack Wiki</a></li> -</ul> -</div> -</div> -</div> -</div> diff --git a/files/ru/mozilla/add-ons/sdk/guides/скрипты_содержимого/index.html b/files/ru/mozilla/add-ons/sdk/guides/скрипты_содержимого/index.html deleted file mode 100644 index 59832331e8..0000000000 --- a/files/ru/mozilla/add-ons/sdk/guides/скрипты_содержимого/index.html +++ /dev/null @@ -1,519 +0,0 @@ ---- -title: Скрипты Content Scripts -slug: Mozilla/Add-ons/SDK/Guides/Скрипты_содержимого -tags: - - Content script - - Дополнение -translation_of: Archive/Add-ons/Add-on_SDK/Guides/Content_Scripts ---- -<article id="wikiArticle"> -<p>{{AddonSidebar}}</p> - -<div class="blockIndicator warning"> -<p>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.</p> -</div> - -<p>{{LegacyAddonsNotice}}</p> - -<p>Многим дополнениям (add-on) необходим доступ к веб-страницам и возможность их изменения. Но основной код дополнения не имеет прямого доступа к веб-содержимому. Взамен, SDK-дополнений необходим способ в коде, который даст доступ к веб-содержимому в отдельных скриптах, которые называются <code>content scripts</code> (скрипты содержимого). Эта страница описывает как разрабатывать и реализовывать <code>content scripts</code>.</p> - -<p>Скрипты <code>content scripts</code>, вероятно, один из наиболее сбивающих с толку аспектов при работе с SDK, но вам они скорее всего будут нужны. Существуют пять основных принципов:</p> - -<ul> - <li>расширения основного кода, включая "main.js" и другие модули в "lib", могут использовать SDK <a href="/en-US/Add-ons/SDK/High-Level_APIs">верхнего-уровня</a> и <a href="/en-US/Add-ons/SDK/Low-Level_APIs">нижнего-уровня</a> API, но не имеют доступа к веб-содержимому напрямую;</li> - <li>скрипты <code>content scripts </code><a href="/en-US/Add-ons/SDK/Guides/Two_Types_of_Scripts#API_Access_for_Add-on_Code_and_Content_Scripts">не могут использовать API в SDK</a> (нет доступа к глобальным <code>exports</code>, <code>require</code>) но есть доступ к веб-содержимому;</li> - <li>API в SDK которые используют <code>content scripts</code>, например <a href="/en-US/Add-ons/SDK/High-Level_APIs/page-mod">page-mod</a> и <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs">tabs</a>, предоставляют функции, которые позволяют коду расширения загружать скрипты содержимого в веб-страницы;</li> - <li>скрипты <code>content scripts </code>могут быть загружены как строки, но чаще они хранятся как отдельные файлы в папке "data". jpm не создаёт каталог "data" по умолчанию, поэтому вы должны создать его и положить туда ваши скрипты;</li> - <li>API передачи сообщений позволяет основному коду и скриптам <code>content scripts </code>взаимодействовать друг с другом.</li> -</ul> - -<p>Следующее дополнение (полностью завершённое) показывает эти принципы. "main.js" прикрепляет <code>content scripts</code> к текущей вкладке, используя модуль <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs">tabs</a>. В этом случае, <code>content scripts</code> передаётся, как строка. Скрипт <code>content scripts</code> просто заменяет содержимое страницы:</p> - -<pre class="brush: js">// main.js -var tabs = require("sdk/tabs"); -var contentScriptString = 'document.body.innerHTML = "<h1>this page has been eaten</h1>";' - -tabs.activeTab.attach({ - contentScript: contentScriptString -});</pre> - -<p>Следующие высокоуровневые SDK-модули, могут использовать скрипты <code>content scripts </code>для изменения веб-страниц:</p> - -<ul> - <li><a href="/en-US/Add-ons/SDK/High-Level_APIs/page-mod">page-mod</a>: позволяет вам прикреплять <code>content scripts</code> к веб-страницам, которые соответствуют заданному URL шаблону.</li> - <li><a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs">tabs</a>: экспортирует объект <code>Tab</code> для работы с вкладкой браузера. <code>Tab-объект включает</code> функцию <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs#attach(options)"><code>attach()</code></a>, которая позволяет прикрепить <code>content scripts</code> ко вкладке.</li> - <li><a href="/en-US/Add-ons/SDK/High-Level_APIs/page-worker">page-worker</a>: позволяет вам получить страницу, без отображения её. Вы можете прикрепить <code>content scripts</code> к странице, чтобы иметь доступ и возможность изменять DOM страницы.</li> - <li><a href="/en-US/Add-ons/SDK/High-Level_APIs/context-menu">context-menu</a>: использует <code>content scripts</code> для взаимодействия со страницей, в которой вызывается меню.</li> -</ul> - -<p>В дополнение к этому, некоторые SDK компоненты пользовательского интерфейса - <code>panel, sidebar, frame</code> - заданы в помощью HTML, и необходимо использовать отдельные скрипты для взаимодействия с их контентом. В большинстве случаев они похожи на скрипты <code>content scripts</code>, но в данной статье они не описываются. Для изучения способов взаимодействия с данными модулями пользовательского интерфейса обратитесь к документации: <a href="/en-US/Add-ons/SDK/High-Level_APIs/panel">panel</a>, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_sidebar">sidebar</a>, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_frame">frame</a>.</p> - -<p>Почти все примеры дополнений, представленных в этом руководстве, доступны в полнофункциональном, но минимально необходимом, виде. На GitHub: <a href="https://github.com/mdn/addon-sdk-content-scripts">addon-sdk-content-scripts repository</a>.</p> - -<h2 id="Загрузка_content_scripts">Загрузка content scripts</h2> - -<article id="wikiArticle"> -<p>Вы можете загрузить одиночный скрипт посредством задания строкового атрибута <code>contentScript</code> или <code>contentScriptFile.</code> Атрибут<code> contentScript</code> определяет строковое значение как сам скрипт:</p> - -<pre class="brush: js">// 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 -});</pre> - -<p>Атрибут <code>contentScriptFile</code> определяет строковое значение как путь к ресурсу<code>://<em>URL-путь к скрипту, который находится в подкаталоге вашего дополнения</em>.</code> jpm не создаёт папку "data" по умолчанию, поэтому вы должны добавить её и положить внутрь файл <code>content scripts</code>.</p> - -<p>Следующее дополнение использует URL для ссылки на файл "content-script.js", находящийся в папке <code>data </code>в корне дополнения.</p> - -<pre class="brush: js">// 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") -});</pre> - -<pre class="brush: js">// content-script.js - -document.body.innerHTML = "<h1>Page matches ruleset</h1>";</pre> - -<div class="note"> -<p>Начиная с Firefox 34 и далее , вы можете использовать "./content-script.js" как синоним для self.data.url("content-script.js"). Поэтому можно переписать код main.js, указанный выше, следующим образом:</p> - -<pre class="brush: js">var pageMod = require("sdk/page-mod"); - -pageMod.PageMod({ - include: "*.mozilla.org", - contentScriptFile: "./content-script.js" -}); -</pre> -</div> - -<div class="warning"> -<p>Настоятельно рекоммендуется использовать <code>contentScript </code>только для очень простых скриптов или статичных строк: если это не так, то могут возникнуть проблемы с принятием Вашего дополнения на AMO (<span class="st">addons.<em>mozilla</em>.org</span>).</p> - -<p>Содержите ваши скрипты в отдельном файле и загружайте их, используя <code>contentScriptFile</code>. Это сделает ваш код проще в поддержке, отладке, безопаснее, удобочитаемее.</p> -</div> - -<p>Для любого из параметров<code> contentScript</code> или <code>contentScriptFile</code> вы можете загружать несколько скриптов, передавая массив строк:</p> - -<pre class="brush: js">// 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");'] - }); -}); -</pre> - -<pre class="brush: js">// 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")] -});</pre> - -<p>Если так сделать, то скрипты смогут взаимодействовать друг с другом, как скрипты загружаемые на одной web-странице.</p> - -<p>Можно использовать параметры <code>contentScript</code> and <code>contentScriptFile </code>одновременно. В таком случае скрипты, загружаемые <code>contentScriptFile</code> загрузятся до <code>contentScript. </code>Это похволяет загружать библиотеки JavaScript, такие как jQuery по URL, а затем использвать их в простом скрипте, загруженном через <code>contentScript</code>:</p> - -<pre class="brush: js">// 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") -});</pre> - -<div class="warning"> -<p>Настоятельно рекоммендуется использовать <code>contentScript </code>только для очень простых скриптов или статичных строк: если это не так, то могут возникнуть проблемы с принятием Вашего дополнения на AMO (<span class="st">addons.<em>mozilla</em>.org</span>).</p> - -<p>Содержите ваши скрипты в отдельном файле и загружайте их, используя <code>contentScriptFile</code>. Это сделает ваш код проще в поддержке, отладке, безопаснее, удобочитаемее.</p> -</div> - -<h3 id="Определение_момента_(времени)_подключения_скрипта">Определение момента (времени) подключения скрипта</h3> - -<p>Опция <code>contentScriptWhen </code>определяет момент, когда <code>content script</code> должен быть загружен. Возможные варианты:</p> - -<ul> - <li><code>"start"</code>: загрузить сразу после того, как элемент документа страницы вставляется в DOM. В таком случае DOM-контент ещё пока не загружен, поэтому скрипт не может работать с ним.</li> - <li><code>"ready"</code>: загрузить скрипт после того, как DOM страницы загружен: то есть в точке активации событий <a href="https://developer.mozilla.org/en/Gecko-Specific_DOM_Events">DOMContentLoaded</a>. В этот момент content scripts уже могут взаимодействовать с DOM-контентом, но загрузка внешних CSS и картинок ещё могла не завершиться.</li> - <li><code>"end"</code>: загрузить скрипт после завершения загрузки всего контента (DOM, JS, CSS, картинки), в то время, как активируется событие <a href="https://developer.mozilla.org/en/DOM/window.onload">window.onload event</a>.</li> -</ul> - -<p>Значение по умолчанию <code>"<strong>end</strong>"</code>.</p> - -<p>Обратите внимание, что <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs#attach(options)"><code>tab.attach()</code></a> не имеет параметра <code>contentScriptWhen</code>, потому что он обычно вызывается после загрузки страницы.<a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs#attach(options)"><code> </code></a></p> - -<h3 id="Передача_конфигурационных_опций">Передача конфигурационных опций</h3> - -<p><code>Атрибут contentScriptOptions</code> это JSON-объект, который используется скриптом как read-only значение доступное через свойство <code><a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/self">self</a>.options</code>:</p> - -<pre class="brush: js">// main.js - -var tabs = require("sdk/tabs"); - -tabs.on('ready', function(tab) { - tab.attach({ - contentScript: 'window.alert(self.options.message);', - contentScriptOptions: {"message" : "hello world"} - }); -});</pre> - -<p>Могут быть использованы любые варианты JSON-объектов (object, array, string, etc.).</p> - -<h2 id="Доступ_к_DOM">Доступ к DOM</h2> - -<p>Скрипты <code>content scripts</code> могут иметь доступ к DOM страницы, конечно, только те скрипты, которые уже загрузились на странице. При этом скрипты content scripts изолированы от скриптов web-страницы:</p> - -<ul> - <li>content scripts не видят объектов JavaScript, добавленных скриптами web-страницы.</li> - <li>Если скриты web-страницы переопределят поведения каких-либо DOM-объектов, то скрипты <code>content script</code> обнаружат исходное поведение.</li> -</ul> - -<p>То же происходит в обратную сторону: скрипты web-страницы не увидят объектов JavaScript, добавленных скриптами <code>content scripts</code>.</p> - -<p>Например, рассмотрим страницу, где скрипты web-страницы создают переменную <code>foo </code>в объекте <code>window</code>:</p> - -<pre class="brush: html"><!DOCTYPE html"> -<html> - <head> - <script> - window.foo = "hello from page script" - </script> - </head> -</html></pre> - -<p>Другой скрипт (но тоже page-script), загруженный на страницу после этого скрипта (указанного выше), будет иметь доступ к foo. Но скрипт <code>content script</code> нет:</p> - -<pre class="brush: js">// 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);</pre> - -<pre>console.log: my-addon: null -</pre> - -<p>Есть веские причины для изоляции. Во-первых, из <code>content script</code> не утекают объекты в web-страницу, что потенциально является дырой в безопасности. Во-вторых, <code>content scripts</code> могут не беспокоиться о пересечении объектов с объектами, созданных скриптами web-страницы.</p> - -<p>Такая изоляция необходима, например, в случае, если web-страница загружает библиотеку jQuery, но <code>content script</code> не увидит объектов, созданных этой библиотекой. В этом случае content script может добавить свою собственный jQuery-объект, который не пересечётся со страничным объектом.</p> - -<h3 id="Взаимодействие_со_скриптами_web-страницы">Взаимодействие со скриптами web-страницы</h3> - -<p>Обычно изоляция content scripts и page scripts (скрипты web-страницы) необходима. Но иногда вы захотите наладить такое взаимодействие: вы можете захотеть иметь общие объекты между <code>content scripts</code> и <code>page scripts</code> или передевать между ними сообщения. Если появится такая необходимость, то прочтите о <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/Interacting_with_page_scripts">взаимодействии со скриптами web-страницы</a> (<a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/Interacting_with_page_scripts">interacting with page scripts</a>).</p> - -<h3 id="Прослушивание_событий">Прослушивание событий</h3> - -<p>Вы можете прослушивать события DOM в скриптах <code>content scripts</code> также, как в обычных скриптах web-страницы. Но есть два важных отличия:</p> - -<p>Первое. Если вы определите слушатель через передачу строки в функцию<a href="https://developer.mozilla.org/en/DOM/element.setAttribute"><code> setAttribute()</code></a>, то слушатель будет вызываться в контексте web-страницы, поэтому он не будет иметь доступа ни к каким переменным, определённым в <code>content script</code>.</p> - -<p>Например, при выполнении в данном <code>content script</code> появится ошибка "theMessage is not defined":</p> - -<pre class="brush: js">var theMessage = "Hello from content script!"; -anElement.setAttribute("onclick", "alert(theMessage);");</pre> - -<p>Второе. Если вы определите слушатель напрямую через <a href="/en-US/docs/Web/API/GlobalEventHandlers">GlobalEventHandlers</a>, например на <code>onclick</code>, то такое определение может быть переопределено на web-странице. Например, здесь представлен add-on, который пытается добавить обработчик click-события при помощи присвоения <code>window.onclick</code>:</p> - -<pre class="brush: js">var myScript = "window.onclick = function() {" + - " console.log('unsafewindow.onclick: ' + window.document.title);" + - "}"; - -require("sdk/page-mod").PageMod({ - include: "*", - contentScript: myScript, - contentScriptWhen: "start" -});</pre> - -<p>Это всё будет прекрасно работать на многих страницах, но не сработает там, где также присваивается <code>onclick</code>:</p> - -<pre class="brush: html"><html> - <head> - </head> - <body> - <script> - window.onclick = function() { - window.alert("it's my click now!"); - } - </script> - </body> -</html></pre> - -<p>По этим причинам, лучший вариант для добавления слушалелей это использование <a href="https://developer.mozilla.org/en/DOM/element.addEventListener"><code>addEventListener()</code></a>, определяющем функцию:</p> - -<pre class="brush: js">var theMessage = "Hello from content script!"; - -anElement.onclick = function() { - alert(theMessage); -}; - -anotherElement.addEventListener("click", function() { - alert(theMessage); -});</pre> - -<h2 id="Взаимодействие_с_скриптом_дополнения_(add-on)">Взаимодействие с скриптом дополнения (add-on)</h2> - -<p>Для организации взаимодействия друг с другом скрипта дополнения (<code>add-on script</code>) и скрипта <code>content script</code> нужно обоим дать доступ к объекту <code>port</code>.</p> - -<ul> - <li>для отправки сообщений используется <code>port.emit()</code></li> - <li>для получения сообщений - <code>port.on()</code></li> -</ul> - -<p><img alt="" src="https://mdn.mozillademos.org/files/7873/content-scripting-overview.png" style="display: block; margin-left: auto; margin-right: auto;">Сообщения асинхронны: то есть, отправитель не ждёт ответа от получателя, а только отправляет сообщение и продолжает работать дальше.</p> - -<p>Вот пример простого дополнения, которое отправляет сообщение скрипту <code>content script, используя port</code>:</p> - -<pre class="brush: js">// 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");</pre> - -<pre class="brush: js">// content-script.js - -self.port.on("alert", function(message) { - window.alert(message); -});</pre> - -<div class="note"> -<p>Модуль <code>context-menu</code> не использует данную модель коммуникации. Для изучения варианта взаимодействия скриптов <code>content scripts</code>, загруженных с использованием <code>context-menu</code>, смотрите <a href="/en-US/Add-ons/SDK/High-Level_APIs/context-menu">context-menu documentation</a>. </p> -</div> - -<h3 id="Доступ_к_порту_в_content_script">Доступ к порту в content script</h3> - -<p>В скрипте <code>content script</code> объект <code>port </code>доступен через свойство глобального объекта <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/self"><code>self</code></a>. Чтобы послать сообщение из <code>content script</code>:</p> - -<pre class="brush: js">self.port.emit("myContentScriptMessage", myContentScriptMessagePayload);</pre> - -<p>Чтобы получить сообщение из кода дополнения:</p> - -<pre class="brush: js">self.port.on("myAddonMessage", function(myAddonMessagePayload) { - // Handle the message -});</pre> - -<div class="note"> -<p><span>Учтите, что глобальный объект <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/self"><code>self</code></a> совершенно отличается от модуля <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/self"><code>self</code> module</a>, предоставляющим API дополнению для доступа к его файлам и ID.</span></p> -</div> - -<h3 id="Доступ_к_порту_в_скрипте_дополнения_(add-on_script)">Доступ к порту в скрипте дополнения (add-on script)</h3> - -<p>В коде дополнения канал взаимодействия между дополнением и конкретным <code>content script</code> инкапсулируется посредством объекта <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/content_worker"><code>worker</code></a>. Поэтому объект <code>port </code>для для связи со скриптом content script это свойство связанного worker.</p> - -<p>Тем не менее, объект worker не расширен на код дополнения так же, как в других модулях.</p> - -<h4 id="Сообщения_из_page-worker">Сообщения из<code> page-worker</code></h4> - -<p>Объект <code>page-worker</code> интегрирует в себе <code>worker API</code>. Поэтому для получения сообщений от скрипта content script, ассоциированного с <code>page-worker нужно использовать </code><code>pageWorker.port.on()</code>:</p> - -<pre class="brush: js">// 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); -});</pre> - -<p>Для отправки пользовательских сообщений их дополнения нужно вызвать <code>pageWorker.port.emit()</code>:</p> - -<pre class="brush: js">// 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");</pre> - -<pre class="brush: js">// 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); - } -}</pre> - -<h4 id="Сообщения_из_page-mod">Сообщения из <code>page-mod</code></h4> - -<p>Один объект <code>page-mod</code> может привязать свои скрипты к нескольким страницам, каждая из них со своим контекстом, в котором запускаются <code>content scripts</code>. Поэтому для каждой страницы необходим отдельный канал (<code>worker</code>) связи.</p> - -<p><code>page-mod</code> не интегрирует в себе <code>worker API напрямую</code>. Вместо этого, когда скрипт <code>content script</code> привязывается к странице, <code>page-mod</code> бросает событие <code>attach</code> тому слушателю, который связан с worker. Создавая слушатель для события <code>attach</code>, вы можете получить доступ через объект <code>port </code>к тому скрипту <code>content scripts</code>, который связан с нужной страницей (через <code>page-mod)</code>:</p> - -<pre class="brush: js">// 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'); - }); -}</pre> - -<pre class="brush: js">// 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); -}); -</pre> - -<p>В дополнении, описанном выше, есть два сообщения:</p> - -<ul> - <li><code>click</code> отправляется из <code>page-mod</code> в дополнение, когда пользователь кликает на элемент на web-странице</li> - <li><code>warning</code> отправляет прикольную строчку обратно в объект <code>page-mod</code></li> -</ul> - -<h4 id="Сообщения_из_Tab.attach()">Сообщения из <code>Tab.attach()</code></h4> - -<p>Функция <code>Tab.attach()</code> возвращает <code>worker</code>, который можно использовать для связи со скриптом content script(s).</p> - -<p>Следующее дополнение добавляет кнопку в Firefox: когда пользователь надимает её, то дополнение привязывает скрипт <code>content script</code> к активной вкладке, отправляет этому скрипту сообщение "my-addon-message" и ждёт ответ "my-script-response":</p> - -<pre class="brush: js">//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"); -} -</pre> - -<pre class="brush: js">// 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"); -}</pre> - -<h3 id="Описание_port_API">Описание port API</h3> - -<p>Смотрите <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/port">reference page for the <code>port</code> object</a>.</p> -</article> - -<h3 id="Описание_postMessage_API">Описание postMessage API</h3> - -<p>До того, как был введён объект port, дополнения и <code>content scripts </code>общались следующим образом, используя различные API:</p> - -<ul> - <li>скрипт content script <code>вызывал self.postMessage()</code> для отправки и <code>self.on()</code> для получения</li> - <li>дополнение (add-on) вызывал <code>worker.postMessage()</code> для отправки и <code>worker.on()</code> для получения</li> -</ul> - -<p>Данный API до сих пор доступно и <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/using_postMessage">документировано</a>, но желательно использовать <code>port API</code>, описанный здесь выше. Исключением является модуль <a href="/en-US/Add-ons/SDK/High-Level_APIs/context-menu">context-menu</a>, который ещё использует <code>postMessage</code>.</p> - -<h3 id="Взаимодействие_скриптов_content_script_со_скриптами_content_script">Взаимодействие скриптов content script со скриптами content script</h3> - -<p>Скрипты <code>content scripts</code> могут взаимодействовать друг с другом напрямую если они загружены в одном контексте. Например, если один вызов <code>Tab.attach()</code> привязывает два скрипта <code>content scripts</code>, то они видят друг друга напрямую, как если два скрипта загружены на одну страницу. Но если вызвать <code>Tab.attach()</code> дважды, привязывая <code>content scripts</code> каждый раз, то они уже не будут загружены в одном контексте, и дожны взаимодействовать способами как скрипты из разных контекстов. Один из вариантом это пересылать сообщения через основной код дополнения, используя port API с передачей сообщения другим скриптам <code>context script</code>. Этои вариант будет работать независимо от контекста, в котором загружен скрипт <code>content script</code>.</p> - -<p>В отдельном случае, когда два скрипта загружены на одной странице, существует возможность для обоих скриптов <code>content scripts</code> взаимодействовать друг с другом, используя<a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/Communicating_With_Other_Scripts#Using_the_DOM_postMessage_API"> DOM postMessage() API</a> или <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent">CustomEvent</a>. Следующее дополнение показывает как скрипт <code>content script</code>, добавленный через <code>page-mod</code>, получает событие CustomEvent, отправленное из <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/SDK/High-Level_APIs/context-menu">context-menu</a>, когда элемент меню был кликнут. Скрипт <code>page-mod</code> будет отображать алерт с URL той ссылки, по которой было отображено контекстное меню. URL передан в скрипт <code>page-mod</code> с использованием CustomEvent.</p> - -<pre><code>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);' - + '});' -});</code></pre> - -<h2 id="Междоменные_скрипты_content_script">Междоменные скрипты <code>content script</code></h2> - -<p>По умолчанию скрипты <code>content script </code>не имеют никаких междоменных привилегий. В частности, они не имеют доступа к содержимому в <code>iframe</code>, если содержимое получено из другого домена, или выполняются междоменные XMLHttpRequests.</p> - -<p>Однако, вы можете разрешить эти функции для заданных доменов, путём добавления их в <a href="/en-US/Add-ons/SDK/Tools/package_json">package.json</a> дополнения в ключе <code>"cross-domain-content"</code>, который расположен в ключе <code>"permissions"</code>. Смотрите статью <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/Cross_Domain_Content_Scripts">междоменные скрипты содержимого</a>.</p> -</article> diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html deleted file mode 100644 index 069cb199b2..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/addon-page/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Страницы дополнения -slug: Mozilla/Add-ons/SDK/High-Level_APIs/addon-page -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/addon-page ---- -<p>{{AddonSidebar}}</p> - -<p>{{obsolete_header(35)}}</p> - -<p>Создание простых страниц</p> - -<h2 id="Применеие">Применеие</h2> - -<p>С помошью Add-on SDK Вы можете представлять данные пользователю, такие как руководство по использованию вашего дополнения во вкладке браузера. Вы можете подгружать содержимое из HTML файла в "data" директории дополнения.</p> - -<div class="note"> -<p><strong>Заметка:</strong> Данный модульне влияет на браузер.</p> -</div> - -<p>Для подобных страниц, navigational elements such as the <a href="http://support.mozilla.org/en-US/kb/Location%20bar%20autocomplete">Awesome Bar</a>, <a href="http://support.mozilla.org/en-US/kb/Search%20bar">Search Bar</a>, or <a href="http://support.mozilla.org/en-US/kb/Bookmarks%20Toolbar">Bookmarks Toolbar</a> are not usually relevant and distract from the content you are presenting. The <code>addon-page</code> module provides a simple way to have a page which excludes these elements.</p> - -<p>Чтобы импортировать содержимое, используйте <code>require()</code>. После чего, данные загрузятся из "data/index.html" без элементов навигации:</p> - -<pre class="brush: js">var addontab = require("sdk/addon-page"); -var data = require("sdk/self").data; - -require("sdk/tabs").open(data.url("index.html")); -</pre> - -<p><img alt="" src="https://mdn.mozillademos.org/files/6503/addon-page.png" style="display: block; height: 722px; margin-left: auto; margin-right: auto; width: 666px;"></p> - -<p>Это влияет только на "data/index.html": остальные страницы отображаются нормально.</p> diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html deleted file mode 100644 index 2d88abc734..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html +++ /dev/null @@ -1,578 +0,0 @@ ---- -title: context-menu -slug: Mozilla/Add-ons/SDK/High-Level_APIs/context-menu -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/context-menu ---- -<div class="note"> - <p>Stable</p> -</div> -<p><span class="seoSummary">Как добавить элемент меню, подменю и разделитель в контекстное меню страницы.</span></p> -<h2 id="Использование">Использование</h2> -<p>Instead of manually adding items when particular contexts occur and then removing them when those contexts go away, you <em>bind</em> 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.</p> -<p>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.</p> -<p>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 <code>extensions.addon-sdk.context-menu.overflowThreshold</code> preference) all of the menu items will instead appear in an overflow menu to avoid making the context menu too large.</p> -<h3 id="Specifying_Contexts">Specifying Contexts</h3> -<p>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.</p> -<p>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.</p> -<h4 id="The_Page_Context">The Page Context</h4> -<p>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.</p> -<p>The <em>page context</em> 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.</p> -<p>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.</p> -<h4 id="Declarative_Contexts">Declarative Contexts</h4> -<p>You can specify some simple, declarative contexts when you create a menu item by setting the <code>context</code> property of the options object passed to its constructor, like this:</p> -<pre class="brush: js">var cm = require("sdk/context-menu"); -cm.Item({ - label: "My Menu Item", - context: cm.URLContext("*.mozilla.org") -});</pre> -<table class="standard-table"> - <tbody> - <tr> - <th>Constructor</th> - <th>Description</th> - </tr> - <tr> - <td><code>PageContext() </code></td> - <td>The page context.</td> - </tr> - <tr> - <td><code>SelectionContext() </code></td> - <td>This context occurs when the menu is invoked on a page in which the user has made a selection.</td> - </tr> - <tr> - <td><code>SelectorContext(selector) </code></td> - <td>This context occurs when the menu is invoked on a node that either matches <code>selector</code>, a CSS selector, or has an ancestor that matches. <code>selector</code> may include multiple selectors separated by commas, e.g., <code>"a[href], img"</code>.</td> - </tr> - <tr> - <td><code>URLContext(matchPattern) </code></td> - <td>This context occurs when the menu is invoked on pages with particular URLs. <code>matchPattern</code> is a match pattern string or an array of match pattern strings. When <code>matchPattern</code> 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 <a href="/en-US/Add-ons/SDK/High-Level_APIs/page-mod"><code>page-mod</code></a> <code>include</code> property. <a href="/en-US/Add-ons/SDK/Low-Level_APIs/util_match-pattern">Read more about patterns</a>.</td> - </tr> - <tr> - <td><code>PredicateContext(predicateFunction)</code></td> - <td><code>predicateFunction</code> 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.</td> - </tr> - <tr> - <td>array</td> - <td>An array of any of the other types. This context occurs when all contexts in the array occur.</td> - </tr> - </tbody> -</table> -<p>Menu items also have a <code>context</code> property that can be used to add and remove declarative contexts after construction. For example:</p> -<pre class="brush: js">var context = require("sdk/context-menu").SelectorContext("img"); -myMenuItem.context.add(context); -myMenuItem.context.remove(context);</pre> -<p>When a menu item is bound to more than one context, it appears in the menu when all of those contexts occur.</p> -<h3 id="In_Content_Scripts">In Content Scripts</h3> -<p>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.</p> -<p>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 <code>context-menu</code> API uses <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts">content scripts</a> 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.</p> -<p>A special event named <code>"context"</code> 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.</p> -<p>For example, this item appears whenever the context menu is invoked on a page that contains at least one image:</p> -<pre class="brush: js">require("sdk/context-menu").Item({ - label: "This Page Has Images", - contentScript: 'self.on("context", function (node) {' + - ' return !!document.querySelector("img");' + - '});' -});</pre> -<p>Note that the listener function has a parameter called <code>node</code>. 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.</p> -<p>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.</p> -<p>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 <code>node</code> will always be an image:</p> -<pre class="brush: js">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);' + - '});' -});</pre> -<p>However, if you do combine <code>SelectorContext</code> and the <code>"context"</code> event, be aware that the <code>node</code> argument passed to the <code>"context"</code> event will not always match the type specified in <code>SelectorContext</code>.</p> -<p><code>SelectorContext</code> will match if the menu is invoked on the node specified <em>or any descendant of that node</em>, but the <code>"context"</code> event handler is passed <em>the actual node</em> on which the menu was invoked. The example above works because <code><IMG></code> elements can't contain other elements, but in the example below, <code>node.nodeName</code> is not guaranteed to be "P" - for example, it won't be "P" if the user context-clicked a link inside a paragraph:</p> -<pre class="brush: js">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;' + - '});' -});</pre> -<p>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.</p> -<h3 id="Handling_Menu_Item_Clicks">Handling Menu Item Clicks</h3> -<p>In addition to using content scripts to listen for the <code>"context"</code> event as described above, you can use content scripts to handle item clicks. When the user clicks your menu item, an event named <code>"click"</code> is emitted in the item's content script.</p> -<p>Therefore, to handle an item click, listen for the <code>"click"</code> event in that item's content script like so:</p> -<pre class="brush: js">require("sdk/context-menu").Item({ - label: "My Item", - contentScript: 'self.on("click", function (node, data) {' + - ' console.log("Item clicked!");' + - '});' -});</pre> -<p>Note that the listener function has parameters called <code>node</code> and <code>data</code>.</p> -<h4 id="The_node_Argument">The "node" Argument</h4> -<p><code>node</code> is the node that the user context-clicked to invoke the menu.</p> -<ul> - <li>If you did not use <code>SelectorContext</code> to decide whether to show the menu item, then this is the actual node clicked.</li> - <li>If you did use <code>SelectorContext</code>, then this is the node that matched your selector.</li> -</ul> -<p>For example, suppose your add-on looks like this:</p> -<pre class="brush: js">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 -});</pre> -<p>This add-on creates a context-menu item that uses <code>SelectorContext</code> to display the item whenever the context menu is activated on any descendant of the <code><BODY></code> element. When clicked, the item just logs the <a href="https://developer.mozilla.org/en-US/docs/DOM/Node.nodeName"><code>nodeName</code></a> property for the node passed to the click handler.</p> -<p>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:</p> -<pre>info: contextmenu-example: clicked: BODY</pre> -<p>By contrast, this add-on uses the <code>PageContext</code>:</p> -<pre class="brush: js">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 -});</pre> -<p>It will log the name of the actual node clicked:</p> -<pre>info: contextmenu-example: clicked: P</pre> -<h4 id="The_data_Argument">The "data" Argument</h4> -<p><code>data</code> is the <code>data</code> 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 <code>data</code> value passed matches the item you expect. You can use this to simplify click handling by providing just a single click listener on a <code>Menu</code> that reacts to clicks for any child items.:</p> -<pre class="brush: js">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" }) - ] -}); -</pre> -<h4 id="Communicating_With_the_Add-on">Communicating With the Add-on</h4> -<p>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 <code>postMessage</code> function attached to the global <code>self</code> object, passing it some JSON-able data. The menu item's <code>"message"</code> event listener will be called with that data.</p> -<pre class="brush: js">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); - } -});</pre> -<h3 id="Updating_a_Menu_Item's_Label">Updating a Menu Item's Label</h3> -<p>Each menu item must be created with a label, but you can change its label later using a couple of methods.</p> -<p>The simplest method is to set the menu item's <code>label</code> property. This example updates the item's label based on the number of times it's been clicked:</p> -<pre class="brush: js">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. - } -});</pre> -<p>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 <code>"context"</code> 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 <code>"context"</code> listeners can also return strings. When a <code>"context"</code> listener returns a string, it becomes the item's new label.</p> -<p>This item implements the aforementioned search example:</p> -<pre class="brush: js">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;' + - '});' -});</pre> -<p>The <code>"context"</code> 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 <code>text</code>", where <code>text</code> is the truncated selection.</p> -<h3 id="Private_Windows">Private Windows</h3> -<p>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.</p> -<p>To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the <a href="/en-US/Add-ons/SDK/High-Level_APIs/private-browsing">documentation for the <code>private-browsing</code> module</a>.</p> -<h3 id="More_Examples">More Examples</h3> -<p>For conciseness, these examples create their content scripts as strings and use the <code>contentScript</code> property. In your own add-on, you will probably want to create your content scripts in separate files and pass their URLs using the <code>contentScriptFile</code> property. See <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts">Working with Content Scripts</a> for more information.</p> -<div class="warning"> - <p>Unless your content script is extremely simple and consists only of a static string, don't use <code>contentScript</code>: if you do, you may have problems getting your add-on approved on AMO.</p> - <p>Instead, keep the script in a separate file and load it using <code>contentScriptFile</code>. This makes your code easier to maintain, secure, debug and review.</p> -</div> -<p>Show an "Edit Page Source" item when the user right-clicks a non-interactive part of the page:</p> -<pre class="brush: js">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); - } -});</pre> -<p>Show an "Edit Image" item when the menu is invoked on an image:</p> -<pre class="brush: js">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); - } -});</pre> -<p>Show an "Edit Mozilla Image" item when the menu is invoked on an image in a mozilla.org or mozilla.com page:</p> -<pre class="brush: js">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); - } -});</pre> -<p>Show an "Edit Page Images" item when the page contains at least one image:</p> -<pre class="brush: js">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); - } -});</pre> -<p>Show a "Search With" menu when the user right-clicks an anchor that searches Google or Wikipedia with the text contained in the anchor:</p> -<pre class="brush: js">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] -});</pre> -<h2 id="Globals">Globals</h2> -<h3 id="Constructors">Constructors</h3> -<h4 class="addon-sdk-api-name" id="Item(options)"><code>Item(options)</code></h4> -<p>Creates a labeled menu item that can perform an action when clicked.</p> -<h5 id="Parameters">Parameters</h5> -<p><strong>options : object</strong><br> - Required options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>label</td> - <td>string</td> - <td> - <p>The item's label. It must either be a string or an object that implements <code>toString()</code>.</p> - </td> - </tr> - </tbody> -</table> -<p>Optional options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>image</td> - <td>string</td> - <td> - <p>The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's <code>data</code> directory, or a data URI.</p> - </td> - </tr> - <tr> - <td>data</td> - <td>string</td> - <td> - <p>An optional arbitrary value to associate with the item. It must be either a string or an object that implements <code>toString()</code>. It will be passed to click listeners.</p> - </td> - </tr> - <tr> - <td>context</td> - <td>value</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>contentScript</td> - <td>string,array</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>contentScriptFile</td> - <td>string,array</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>onMessage</td> - <td>function</td> - <td> - <p>If the item is contained in the top-level context menu, this function will be called when the content script calls <code>self.postMessage</code>. It will be passed the data that was passed to <code>postMessage</code>.</p> - </td> - </tr> - </tbody> -</table> -<h4 class="addon-sdk-api-name" id="Menu(options)"><code>Menu(options)</code></h4> -<p>Creates a labeled menu item that expands into a submenu.</p> -<h5 id="Parameters_2">Parameters</h5> -<p><strong>options : object</strong><br> - Required options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>label</td> - <td>string</td> - <td> - <p>The item's label. It must either be a string or an object that implements <code>toString()</code>.</p> - </td> - </tr> - <tr> - <td>items</td> - <td>array</td> - <td> - <p>An array of menu items that the menu will contain. Each must be an <code>Item</code>, <code>Menu</code>, or <code>Separator</code>.</p> - </td> - </tr> - </tbody> -</table> -<p>Optional options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>image</td> - <td>string</td> - <td> - <p>The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's <code>data</code> directory, or a data URI.</p> - </td> - </tr> - <tr> - <td>context</td> - <td>value</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>contentScript</td> - <td>string,array</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>contentScriptFile</td> - <td>string,array</td> - <td> - <p>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.</p> - </td> - </tr> - <tr> - <td>onMessage</td> - <td>function</td> - <td> - <p>If the menu is contained in the top-level context menu, this function will be called when the content script calls <code>self.postMessage</code>. It will be passed the data that was passed to <code>postMessage</code>.</p> - </td> - </tr> - </tbody> -</table> -<h4 class="addon-sdk-api-name" id="Separator()"><code>Separator()</code></h4> -<p>Creates a menu separator.</p> -<h4 class="addon-sdk-api-name" id="PageContext()"><code>PageContext()</code></h4> -<p>Creates a page context. See Specifying Contexts above.</p> -<h4 class="addon-sdk-api-name" id="SelectionContext()"><code>SelectionContext()</code></h4> -<p>Creates a context that occurs when a page contains a selection. See Specifying Contexts above.</p> -<h4 class="addon-sdk-api-name" id="SelectorContext(selector)"><code>SelectorContext(selector)</code></h4> -<p>Creates a context that matches a given CSS selector. See Specifying Contexts above.</p> -<h5 id="Parameters_3">Parameters</h5> -<p><strong>selector : string</strong><br> - A CSS selector.</p> -<h4 class="addon-sdk-api-name" id="URLContext(matchPattern)"><code>URLContext(matchPattern)</code></h4> -<p>Creates a context that matches pages with particular URLs. See Specifying Contexts above.</p> -<h5 id="Parameters_4">Parameters</h5> -<p><strong>matchPattern : string,array</strong><br> - A <a href="/en-US/Add-ons/SDK/Low-Level_APIs/util_match-pattern">match pattern</a> string, regexp or an array of match pattern strings or regexps.</p> -<h4 class="addon-sdk-api-name" id="PredicateContext(predicateFunction)"><code>PredicateContext(predicateFunction)</code></h4> -<div class="geckoVersionNote"> - <p>New in Firefox 29</p> -</div> -<p>Creates a context that occurs when predicateFunction returns a true value. See Specifying Contexts above.</p> -<h5 id="Parameters_5">Parameters</h5> -<p><strong>predicateFunction : function(context)</strong><br> - A function which will be called with an object argument that provide information about the invocation context. <code>context</code> object properties:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Property</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>documentType</code></td> - <td>The MIME type of the document the menu was invoked in. E.g. <code>text/html</code> for HTML pages, <code>application/xhtml+xml</code> for XHTML, or <code>image/jpeg</code> if viewing an image directly.</td> - </tr> - <tr> - <td><code>documentURL</code></td> - <td>The URL of the document the menu was invoked in.</td> - </tr> - <tr> - <td><code>targetName</code></td> - <td>The name of the DOM element that the menu was invoked on, in lower-case.</td> - </tr> - <tr> - <td><code>targetID</code></td> - <td>The <code>id</code> attribute of the element that the menu was invoked on, or <code>null</code> if not set.</td> - </tr> - <tr> - <td><code>isEditable</code></td> - <td><code>true</code> 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 <code>contenteditable</code> attribute set to <code>true</code>.</td> - </tr> - <tr> - <td><code>selectionText</code></td> - <td>The current selection as a text string, or <code>null</code>. 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.</td> - </tr> - <tr> - <td><code>srcURL</code></td> - <td>The <code>src</code> URL of the element that the menu was invoked on, or <code>null</code> if it doesn't have one.</td> - </tr> - <tr> - <td><code>linkURL</code></td> - <td>The <code>href</code> URL of the element that the menu was invoked on, or <code>null</code> if it doesn't have one.</td> - </tr> - <tr> - <td><code>value</code></td> - <td>The current contents of a input text box or area if the menu was invoked in one, <code>null</code> otherwise.</td> - </tr> - </tbody> -</table> -<h2 id="Item">Item</h2> -<p>A labeled menu item that can perform an action when clicked.</p> -<h3 id="Methods">Methods</h3> -<h4 class="addon-sdk-api-name" id="destroy()"><code>destroy()</code></h4> -<p>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 <code>removeItem()</code> on the parent menu instead.</p> -<h3 id="Properties">Properties</h3> -<h4 class="addon-sdk-api-name" id="label"><code>label</code></h4> -<p>The menu item's label. You can set this after creating the item to update its label later.</p> -<h4 class="addon-sdk-api-name" id="image"><code>image</code></h4> -<p>The item's icon, a string URL. The URL can be remote, a reference to an image in the add-on's <code>data</code> 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 <code>null</code>.</p> -<h4 class="addon-sdk-api-name" id="data"><code>data</code></h4> -<p>An optional arbitrary value to associate with the item. It must be either a string or an object that implements <code>toString()</code>. It will be passed to click listeners. You can set this after creating the item to update its data later.</p> -<h4 class="addon-sdk-api-name" id="context"><code>context</code></h4> -<p>A list of declarative contexts for which the menu item will appear in the context menu. Contexts can be added by calling <code>context.add()</code> and removed by called <code>context.remove()</code>.</p> -<h4 class="addon-sdk-api-name" id="parentMenu"><code>parentMenu</code></h4> -<p>The item's parent <code>Menu</code>, or <code>null</code> 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 <code>addItem()</code> method.</p> -<h4 class="addon-sdk-api-name" id="contentScript"><code>contentScript</code></h4> -<p>The content script or the array of content scripts associated with the menu item during creation.</p> -<h4 class="addon-sdk-api-name" id="contentScriptFile"><code>contentScriptFile</code></h4> -<p>The URL of a content script or the array of such URLs associated with the menu item during creation.</p> -<h3 id="Events">Events</h3> -<h4 class="addon-sdk-api-name" id="message"><code>message</code></h4> -<p>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 <code>self.postMessage()</code>, the message is delivered to the add-on code in the menu item's <code>message</code> event.</p> -<h5 id="Arguments">Arguments</h5> -<p><strong>value</strong> : Listeners are passed a single argument which is the message posted from the content script. The message can be any <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/using_port#JSON-Serializable_Values">JSON-serializable value</a>.</p> -<h2 id="Menu">Menu</h2> -<p>A labeled menu item that expands into a submenu.</p> -<h3 id="Methods_2">Methods</h3> -<h4 class="addon-sdk-api-name" id="addItem(item)"><code>addItem(item)</code></h4> -<p>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.</p> -<h5 id="Parameters_6">Parameters</h5> -<p><strong>item : Item,Menu,Separator</strong><br> - The <code>Item</code>, <code>Menu</code>, or <code>Separator</code> to add to the menu.</p> -<h4 class="addon-sdk-api-name" id="removeItem(item)"><code>removeItem(item)</code></h4> -<p>Removes the given menu item from the menu. If the menu does not contain the item, this method does nothing.</p> -<h5 id="Parameters_7">Parameters</h5> -<p><strong>item : Item,Menu,Separator</strong><br> - The menu item to remove from the menu.</p> -<h4 class="addon-sdk-api-name" id="destroy()_2"><code>destroy()</code></h4> -<p>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 <code>removeItem()</code> on the parent menu instead.</p> -<h3 id="Properties_2">Properties</h3> -<h4 class="addon-sdk-api-name" id="label_2"><code>label</code></h4> -<p>The menu's label. You can set this after creating the menu to update its label later.</p> -<h4 class="addon-sdk-api-name" id="items"><code>items</code></h4> -<p>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.</p> -<h4 class="addon-sdk-api-name" id="image_2"><code>image</code></h4> -<p>The menu's icon, a string URL. The URL can be remote, a reference to an image in the add-on's <code>data</code> 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 <code>null</code>.</p> -<h4 class="addon-sdk-api-name" id="context_2"><code>context</code></h4> -<p>A list of declarative contexts for which the menu will appear in the context menu. Contexts can be added by calling <code>context.add()</code> and removed by called <code>context.remove()</code>.</p> -<h4 class="addon-sdk-api-name" id="parentMenu_2"><code>parentMenu</code></h4> -<p>The menu's parent <code>Menu</code>, or <code>null</code> 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 <code>addItem()</code> method.</p> -<h4 class="addon-sdk-api-name" id="contentScript_2"><code>contentScript</code></h4> -<p>The content script or the array of content scripts associated with the menu during creation.</p> -<h4 class="addon-sdk-api-name" id="contentScriptFile_2"><code>contentScriptFile</code></h4> -<p>The URL of a content script or the array of such URLs associated with the menu during creation.</p> -<h3 id="Events_2">Events</h3> -<h4 class="addon-sdk-api-name" id="message_2"><code>message</code></h4> -<p>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 <code>self.postMessage()</code>, the message is delivered to the add-on code in the menu item's <code>message</code> event.</p> -<h5 id="Arguments_2">Arguments</h5> -<p><strong>value</strong> : Listeners are passed a single argument which is the message posted from the content script. The message can be any <a href="/en-US/Add-ons/SDK/Guides/Content_Scripts/using_port#JSON-Serializable_Values">JSON-serializable value</a>.</p> -<h2 id="Separator">Separator</h2> -<p>A menu separator. Separators can be contained only in <code>Menu</code>s, not in the top-level context menu.</p> -<h3 id="Methods_3">Methods</h3> -<h4 class="addon-sdk-api-name" id="destroy()_3"><code>destroy()</code></h4> -<p>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 <code>removeItem()</code> on the parent menu instead.</p> -<h3 id="Properties_3">Properties</h3> -<h4 class="addon-sdk-api-name" id="parentMenu_3"><code>parentMenu</code></h4> -<p>The separator's parent <code>Menu</code>. This property is read-only. To add the separator to a new menu, call that menu's <code>addItem()</code> method.</p> diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html deleted file mode 100644 index 32b39d045b..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: High-Level APIs -slug: Mozilla/Add-ons/SDK/High-Level_APIs -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs ---- -<p>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.</p> -<p>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) }}</p> diff --git a/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html b/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html deleted file mode 100644 index 535385e895..0000000000 --- a/files/ru/mozilla/add-ons/sdk/high-level_apis/passwords/index.html +++ /dev/null @@ -1,525 +0,0 @@ ---- -title: passwords -slug: Mozilla/Add-ons/SDK/High-Level_APIs/passwords -translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/passwords ---- -<div class="note"> - <p>Stable</p> -</div> -<p><span class="seoSummary">Interact with Firefox's <a href="http://support.mozilla.com/en-US/kb/Remembering%20passwords">Password Manager</a> to add, retrieve and remove stored credentials.</span></p> -<h2 id="Usage">Usage</h2> -<p>A <em>credential</em> is the set of information a user supplies to authenticate herself with a service. Typically a credential consists of a username and a password.</p> -<p>Using this module you can:</p> -<ol> - <li> - <p><strong>Search</strong> 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).</p> - </li> - <li> - <p><strong>Store</strong> credentials in the Password Manager. You can store different sorts of credentials, as outlined in the "Credentials" section below.</p> - </li> - <li> - <p><strong>Remove</strong> stored credentials from the Password Manager.</p> - </li> -</ol> -<h3 id="Credentials">Credentials</h3> -<p>In this API, credentials are represented by objects.</p> -<p>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.</p> -<p>All credential objects include <code>username</code> and <code>password</code> properties. Different sorts of stored credentials include various additional properties, as outlined in this section.</p> -<p>You can use the Passwords API with three sorts of credentials:</p> -<ul> - <li>Add-on credentials</li> - <li>HTML form credentials</li> - <li>HTTP Authentication credentials</li> -</ul> -<h4 id="Add-on_Credential">Add-on Credential</h4> -<p>These are associated with your add-on rather than a particular web site. They contain the following properties:</p> -<table class="standard-table"> - <colgroup> - <col> - </colgroup> - <tbody> - <tr> - <td><code>username</code></td> - <td>The username.</td> - </tr> - <tr> - <td><code>password</code></td> - <td>The password.</td> - </tr> - <tr> - <td><code>url</code></td> - <td> - <p>For an add-on credential, this property is of the form:<br> - <code>addon:<addon-id></code>, where <code><addon-id></code> is the add-on's <a href="/en-US/Add-ons/SDK/Guides/Program_ID"> Program ID</a>.</p> - <p>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 <code>uri</code> property of the <a href="/en-US/Add-ons/SDK/High-Level_APIs/self"><code>self</code></a> module.</p> - </td> - </tr> - <tr> - <td><code>realm</code></td> - <td> - <p>You can use this as a name for the credential, to distinguish it from any other credentials you've stored.</p> - <p>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:</p> - <code>addon:jid0-01mBBFyu0ZAXCFuB1JYKooSTKIc (User Registration)</code></td> - </tr> - </tbody> -</table> -<h4 id="HTML_Form_Credential">HTML Form Credential</h4> -<p>If a web service uses HTML forms to authenticate its users, then the corresponding credential is an HTML Form credential.</p> -<p>It contains the following properties:</p> -<table class="standard-table"> - <colgroup> - <col> - </colgroup> - <tbody> - <tr> - <td><code>username</code></td> - <td>The username.</td> - </tr> - <tr> - <td><code>password</code></td> - <td>The password.</td> - </tr> - <tr> - <td><code>url</code></td> - <td>The URL for the web service which requires the credential. You should omit anything after the hostname and (optional) port.</td> - </tr> - <tr> - <td><code>formSubmitURL</code></td> - <td>The 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 <code>url</code> property.</td> - </tr> - <tr> - <td><code>usernameField</code></td> - <td>The value of the "name" attribute for the form's username field.</td> - </tr> - <tr> - <td><code>passwordField</code></td> - <td>The value of the "name" attribute for the form's password field.</td> - </tr> - </tbody> -</table> -<p>So: given a form at <code>http://www.example.com/login</code> with the following HTML:</p> -<pre class="brush: 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></pre> -<p>The corresponding values for the credential (excluding username and password) should be:</p> -<pre> url: "http://www.example.com" - formSubmitURL: "http://login.example.com" - usernameField: "uname" - passwordField: "pword" -</pre> -<p>Note that for both <code>url</code> and <code>formSubmitURL</code>, the portion of the URL after the hostname is omitted.</p> -<h4 id="HTTP_Authentication_Credential">HTTP Authentication Credential</h4> -<p>These are used to authenticate the user to a web site which uses HTTP Authentication, as detailed in <a href="http://tools.ietf.org/html/rfc2617">RFC 2617</a>. They contain the following properties:</p> -<table class="standard-table"> - <colgroup> - <col> - </colgroup> - <tbody> - <tr> - <td><code>username</code></td> - <td>The username.</td> - </tr> - <tr> - <td><code>password</code></td> - <td>The password.</td> - </tr> - <tr> - <td><code>url</code></td> - <td>The URL for the web service which requires the credential. You should omit anything after the hostname and (optional) port.</td> - </tr> - <tr> - <td><code>realm</code></td> - <td> - <p>The WWW-Authenticate response header sent by the server may include a "realm" field as detailed in <a href="http://tools.ietf.org/html/rfc2617">RFC 2617</a>. If it does, this property contains the value for the "realm" field. Otherwise, it is omitted.</p> - <p>The realm is displayed in Firefox's Password Manager, under "Site", in brackets after the URL.</p> - </td> - </tr> - </tbody> -</table> -<p>So: if a web server at <code>http://www.example.com</code> requested authentication with a response code like this:</p> -<pre> HTTP/1.0 401 Authorization Required - Server: Apache/1.3.27 - WWW-Authenticate: Basic realm="ExampleCo Login" -</pre> -<p>The corresponding values for the credential (excluding username and password) should be:</p> -<pre> url: "http://www.example.com" - realm: "ExampleCo Login" -</pre> -<h3 id="onComplete_and_onError">onComplete and onError</h3> -<p>This API is explicitly asynchronous, so all its functions take two callback functions as additional options: <code>onComplete</code> and <code>onError</code>.</p> -<p><code>onComplete</code> is called when the operation has completed successfully and <code>onError</code> is called when the function encounters an error.</p> -<p>Because the <code>search</code> function is expected to return a list of matching credentials, its <code>onComplete</code> option is mandatory. Because the other functions don't return a value in case of success their <code>onComplete</code> options are optional.</p> -<p>For all functions, <code>onError</code> is optional.</p> -<h2 id="Globals">Globals</h2> -<h3 id="Functions">Functions</h3> -<h4 class="addon-sdk-api-name" id="search(options)"><code>search(options)</code></h4> -<p>This function is used to retrieve a credential, or a list of credentials, stored in the Password Manager.</p> -<p>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 <code>onComplete</code> callback.</p> -<p>So if you pass in an empty set of properties, all stored credentials are returned:</p> -<pre class="brush: js">function show_all_passwords() { - require("sdk/passwords").search({ - onComplete: function onComplete(credentials) { - credentials.forEach(function(credential) { - console.log(credential.username); - console.log(credential.password); - }); - } - }); - }</pre> -<p>If you pass it a single property, only credentials matching that property are returned:</p> -<pre class="brush: js">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); - }); - } - }); - }</pre> -<p>If you pass more than one property, returned credentials must match all of them:</p> -<pre class="brush: js">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); - }); - } - }); - }</pre> -<p>To retrieve only credentials associated with your add-on, use the <code>url</code> property, initialized from <code>self.uri</code>:</p> -<pre class="brush: js">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); - }); - } - }); - }</pre> -<h5 id="Parameters">Parameters</h5> -<p><strong>options : object</strong><br> - Required options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>onComplete</td> - <td>function</td> - <td> - <p>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.</p> - </td> - </tr> - </tbody> -</table> -<p>Optional options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>username</td> - <td>string</td> - <td> - <p>The username for the credential.</p> - </td> - </tr> - <tr> - <td>password</td> - <td>string</td> - <td> - <p>The password for the credential.</p> - </td> - </tr> - <tr> - <td>url</td> - <td>string</td> - <td> - <p>The URL associated with the credential.</p> - </td> - </tr> - <tr> - <td>formSubmitURL</td> - <td>string</td> - <td> - <p>The URL an HTML form credential is submitted to.</p> - </td> - </tr> - <tr> - <td>realm</td> - <td>string</td> - <td> - <p>For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.</p> - </td> - </tr> - <tr> - <td>usernameField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the user name input field in a form.</p> - </td> - </tr> - <tr> - <td>passwordField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the password input field in a form.</p> - </td> - </tr> - <tr> - <td>onError</td> - <td>function</td> - <td> - <p>The callback function that is called if the function failed. The callback is passed an <code>error</code> containing a reason of a failure: this is an <a href="https://developer.mozilla.org/en/nsIException">nsIException</a> object.</p> - </td> - </tr> - </tbody> -</table> -<h4 class="addon-sdk-api-name" id="store(options)"><code>store(options)</code></h4> -<p>This function is used to store a credential in the Password Manager.</p> -<p>It takes an <code>options</code> object as an argument: this contains all the properties for the new credential.</p> -<p>As different sorts of credentials contain different properties, the appropriate options differ depending on the sort of credential being stored.</p> -<p>To store an add-on credential:</p> -<pre class="brush: js">require("sdk/passwords").store({ - realm: "User Registration", - username: "joe", - password: "SeCrEt123", -});</pre> -<p>To store an HTML form credential:</p> -<pre class="brush: js">require("sdk/passwords").store({ - url: "http://www.example.com", - formSubmitURL: "http://login.example.com", - username: "joe", - usernameField: "uname", - password: "SeCrEt123", - passwordField: "pword" -});</pre> -<p>To store an HTTP Authentication credential:</p> -<pre class="brush: js">require("sdk/passwords").store({ - url: "http://www.example.com", - realm: "ExampleCo Login", - username: "joe", - password: "SeCrEt123", -});</pre> -<p>See "Credentials" above for more details on how to set these properties.</p> -<p>The options parameter may also include <code>onComplete</code> and <code>onError</code> callback functions, which are called when the function has completed successfully and when it encounters an error, respectively. These options are both optional.</p> -<h5 id="Parameters_2">Parameters</h5> -<p><strong>options : object</strong><br> - Required options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>username</td> - <td>string</td> - <td> - <p>The username for the credential.</p> - </td> - </tr> - <tr> - <td>password</td> - <td>string</td> - <td> - <p>The password for the credential.</p> - </td> - </tr> - </tbody> -</table> -<p>Optional options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>url</td> - <td>string</td> - <td> - <p>The URL to which the credential applies. Omitted for add-on credentials.</p> - </td> - </tr> - <tr> - <td>formSubmitURL</td> - <td>string</td> - <td> - <p>The URL a form-based credential was submitted to. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>realm</td> - <td>string</td> - <td> - <p>For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.</p> - </td> - </tr> - <tr> - <td>usernameField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the username input in a form. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>passwordField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the password input in a form. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>onComplete</td> - <td>function</td> - <td> - <p>The callback function that is called once the function completes successfully.</p> - </td> - </tr> - <tr> - <td>onError</td> - <td>function</td> - <td> - <p>The callback function that is called if the function failed. The callback is passed an <code>error</code> argument: this is an <a href="https://developer.mozilla.org/en/nsIException">nsIException</a> object.</p> - </td> - </tr> - </tbody> -</table> -<h4 class="addon-sdk-api-name" id="remove(options)"><code>remove(options)</code></h4> -<p>Removes a stored credential. You supply it all the properties of the credential to remove, along with optional <code>onComplete</code> and <code>onError</code> callbacks.</p> -<p>Because you must supply all the credential's properties, it may be convenient to call <code>search</code> first, and use its output as the input to <code>remove</code>. For example, to remove all of joe's stored credentials:</p> -<pre class="brush: js">require("sdk/passwords").search({ - username: "joe", - onComplete: function onComplete(credentials) { - credentials.forEach(require("sdk/passwords").remove); - }) -});</pre> -<p>To change an existing credential just call <code>store</code> after <code>remove</code> succeeds:</p> -<pre class="brush: js">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}" - }) - } -});</pre> -<h5 id="Parameters_3">Parameters</h5> -<p><strong>options : object</strong><br> - Required options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>username</td> - <td>string</td> - <td> - <p>The username for the credential.</p> - </td> - </tr> - <tr> - <td>password</td> - <td>string</td> - <td> - <p>The password for the credential.</p> - </td> - </tr> - </tbody> -</table> -<p>Optional options:</p> -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>url</td> - <td>string</td> - <td> - <p>The URL to which the credential applies. Omitted for add-on credentials.</p> - </td> - </tr> - <tr> - <td>formSubmitURL</td> - <td>string</td> - <td> - <p>The URL a form-based credential was submitted to. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>realm</td> - <td>string</td> - <td> - <p>For HTTP Authentication credentials, the realm for which the credential was requested. For add-on credentials, a name for the credential.</p> - </td> - </tr> - <tr> - <td>usernameField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the username input in a form. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>passwordField</td> - <td>string</td> - <td> - <p>The value of the <code>name</code> attribute for the password input in a form. Omitted for add-on credentials and HTTP Authentication credentials.</p> - </td> - </tr> - <tr> - <td>onComplete</td> - <td>function</td> - <td> - <p>The callback function that is called once the function has completed successfully.</p> - </td> - </tr> - <tr> - <td>onError</td> - <td>function</td> - <td> - <p>The callback function that is called if the function failed. The callback is passed an <code>error</code> argument: this is an <a href="https://developer.mozilla.org/en/nsIException">nsIException</a> object.</p> - </td> - </tr> - </tbody> -</table> -<p> </p> diff --git a/files/ru/mozilla/add-ons/sdk/index.html b/files/ru/mozilla/add-ons/sdk/index.html deleted file mode 100644 index 6c8217da66..0000000000 --- a/files/ru/mozilla/add-ons/sdk/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Add-on SDK -slug: Mozilla/Add-ons/SDK -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK ---- -<p><span id="result_box" lang="ru"><span class="hps">C помощью </span> <span class="hps">SDK</span> <span class="hps">вы можете создавать дополнения для</span></span><span lang="ru"> <span class="hps">Firefox</span> <span>, используя стандартные</span> <span class="atn hps">веб-</span><span>технологии</span><span>:</span> <span class="hps">JavaScript, HTML</span><span>,</span> <span class="hps">CSS</span>. <span>SDK</span> <span class="hps">включает в себя</span> <span class="hps">API-интерфейсы</span> <span class="hps">JavaScript</span><span>, которые можно использовать</span> <span class="hps">для создания</span> дополнений <span class="hps">и инструменты</span> <span class="hps">для</span> <span class="hps">создания, запуска</span><span>,</span> <span class="hps">тестирования</span> <span class="hps">и</span> <span class="hps">упаковки</span> дополнений<span class="hps">.</span></span></p> - -<hr> -<h3 id="Учебники">Учебники</h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials#getting-started">Начало</a></dt> - <dd>Как <a href="/en-US/Add-ons/SDK/Tutorials/Installation">установить SDK</a> и <a href="/en-US/Add-ons/SDK/Tutorials/Getting_Started_With_cfx">использовать CFX</a> для разработки, тестирования и упаковки дополнений.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials#interact-with-the-browser">Взаимодействие с браузером</a></dt> - <dd><a href="/en-US/Add-ons/SDK/Tutorials/Open_a_Web_Page">Открытие веб-страниц</a>, <a href="/en-US/Add-ons/SDK/Tutorials/Listen_For_Page_Load">прослушивание загрузки страницы</a>, и <a href="/en-US/Add-ons/SDK/Tutorials/List_Open_Tabs">список загруженных страниц</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials#development-techniques">Методы разработки</a></dt> - <dd>Узнайте об распространённых методах разработки, таких как <a href="/en-US/Add-ons/SDK/Tutorials/Unit_testing">модульное тестирование</a>, <a href="/en-US/Add-ons/SDK/Tutorials/Logging">регистрация</a>, <a href="/en-US/Add-ons/SDK/Tutorials/Creating_Reusable_Modules">создание повторных модулей</a>, <a href="/ru/docs/%D0%9B%D0%BE%D0%BA%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F">локализация</a>, и <a href="/en-US/Add-ons/SDK/Tutorials/Mobile_development">мобильная разработка</a>.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials#create-user-interfaces">Создание компонентов пользовательского интерфейса</a></dt> - <dd>Создание компонентов пользовательского интерфейса, такие как <a href="/en-US/Add-ons/SDK/Tutorials/Adding_a_Button_to_the_Toolbar">кнопки панели инструментов </a>, <a href="/en-US/Add-ons/SDK/Tutorials/Add_a_Context_Menu_Item">контекстные меню</a>, <a href="/en-US/Add-ons/SDK/Tutorials/Add_a_Menu_Item_to_Firefox">пункты меню</a>, и <a href="/en-US/Add-ons/SDK/Tutorials/Display_a_Popup">диалоговые окна</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials#modify-web-pages">Изменение веб-страниц</a></dt> - <dd>Изменение страниц, которые <a href="/en-US/Add-ons/SDK/Tutorials/Modifying_Web_Pages_Based_on_URL">соответствуют заданному URL шаблону</a> или динамически <a href="/en-US/Add-ons/SDK/Tutorials/Modifying_the_Page_Hosted_by_a_Tab">изменить заданную вкладку</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Annotator">Соединяем всё вместе</a></dt> - <dd>Обучение на примере расширения Комментатор.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Инструкции">Инструкции</h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Guides#contributors-guide">Руководство для разработчика НРП</a></dt> - <dd>Learn <a href="/en-US/Add-ons/SDK/Guides/Getting_Started">how to start contributing</a> to the SDK, and about the most important idioms used in the SDK code, such as <a href="/en-US/Add-ons/SDK/Guides/Modules">modules</a>, <a href="/en-US/Add-ons/SDK/Guides/Classes_and_Inheritance">classes and inheritance</a>, <a href="/en-US/Add-ons/SDK/Guides/Private_Properties">private properties</a>, and <a href="/en-US/Add-ons/SDK/Guides/Content_Processes">content processes</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Guides#sdk-infrastructure">НРП инфраструктура</a></dt> - <dd>Aspects of the SDK's underlying technology: <a href="/en-US/Add-ons/SDK/Guides/Module_structure_of_the_SDK">modules</a>, the <a href="/en-US/Add-ons/SDK/Guides/Program_ID">Program ID</a>, and the rules defining <a href="/en-US/Add-ons/SDK/Guides/Firefox_Compatibility">Firefox compatibility</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Guides/Content_Scripts">Скрипты содержимого</a></dt> - <dd>A detailed guide to working with content scripts.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Guides#sdk-idioms">Особенности НРП</a></dt> - <dd>The SDK's <a href="/en-US/Add-ons/SDK/Guides/Working_with_Events">event framework</a> and the <a href="/en-US/Add-ons/SDK/Guides/Two_Types_of_Scripts">distinction between add-on scripts and content scripts</a>.</dd> - <dt><a href="/en-US/Add-ons/SDK/Guides/XUL_Migration_Guide">XUL перемещение</a></dt> - <dd>A guide to <a href="/en-US/Add-ons/SDK/Guides/XUL_Migration_Guide">porting XUL add-ons to the SDK</a>. This guide includes a <a href="/en-US/Add-ons/SDK/Guides/XUL_vs_SDK">comparison of the two toolsets</a> and a <a href="/en-US/Add-ons/SDK/Guides/Porting_the_Library_Detector">working example</a> of porting a XUL add-on.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Справочник">Справочник</h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/High-Level_APIs">Высокоуровневый ИПП</a></dt> - <dd>Справочная документация для высокоуровневого ИПП в НРП.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tools">Справочник программ</a></dt> - <dd>Справочная документация для <a href="/en-US/Add-ons/SDK/Tools/cfx">cfx программы</a> используемая для разработки, тестирования, и упаковывания расширений, глобальная <a href="/en-US/Add-ons/SDK/Tools/console">console</a> используемая для протоколирования, и файл <a href="/en-US/Add-ons/SDK/Tools/package_json">package.json</a>.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Low-Level_APIs">Низкоуровневый ИПП</a></dt> - <dd>Справочная документация для низкоуровневого ИПП в НРП.</dd> -</dl> -</div> -</div> - -<p> </p> - -<div class="toppageup" id="js-toppageup" style="display: none;"> -<div class="toppageup-link"><span>наверх</span></div> - -<div class="toppageup-add" id="js-toppageup-add"><span>в закладки</span></div> -</div> diff --git a/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html b/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html deleted file mode 100644 index 8cd08458f0..0000000000 --- a/files/ru/mozilla/add-ons/sdk/low-level_apis/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Low-Level APIs -slug: Mozilla/Add-ons/SDK/Low-Level_APIs -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs ---- -<p>Modules in this section implement low-level APIs. These modules fall roughly into three categories:</p> -<ul> - <li> - <p>fundamental utilities such as <a href="/en-US/Add-ons/SDK/Low-Level_APIs/util_collection">collection</a>. Many add-ons are likely to want to use modules from this category.</p> - </li> - <li> - <p>building blocks for higher level modules, such as <a href="/en-US/Add-ons/SDK/Low-Level_APIs/event_core">events</a> and <a href="/en-US/Add-ons/SDK/Low-Level_APIs/content_worker">worker</a>. You're more likely to use these if you are building your own modules that implement new APIs, thus extending the SDK itself.</p> - </li> - <li> - <p>privileged modules that expose powerful low-level capabilities such as <a href="/en-US/Add-ons/SDK/Low-Level_APIs/window_utils">window/utils</a> and <a href="/en-US/Add-ons/SDK/Low-Level_APIs/net_xhr">net/xhr</a>. You can use these modules in your add-on if you need to, but should be aware that the cost of privileged access is the need to take more elaborate security precautions. In many cases these modules have simpler, more restricted analogs among the "High-Level APIs" (for example, <a href="/en-US/Add-ons/SDK/High-Level_APIs/windows">windows</a> or <a href="/en-US/Add-ons/SDK/High-Level_APIs/request">request</a>).</p> - </li> -</ul> -<p>These modules are still in active development, and we expect to make incompatible changes to them in future releases.</p> -<p>{{ LandingPageListSubpages ("/en-US/Add-ons/SDK/Low-Level_APIs", 5) }}</p> -<p> </p> diff --git a/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html b/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html deleted file mode 100644 index 299e234fb2..0000000000 --- a/files/ru/mozilla/add-ons/sdk/low-level_apis/places_bookmarks/index.html +++ /dev/null @@ -1,595 +0,0 @@ ---- -title: places/bookmarks -slug: Mozilla/Add-ons/SDK/Low-Level_APIs/places_bookmarks -translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/places_bookmarks ---- -<div class="note"> -<p>Unstable</p> -</div> - -<p><span class="seoSummary">Создание, изменение и удаление закладок.</span></p> - -<h2 id="Usage">Usage</h2> - -<p>Этот модуль экспортирует:</p> - -<ul> - <li>три конструктора: <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Bookmark(options)">Bookmark</a>, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Group(options)">Group</a>, and <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Separator(options)">Separator</a>, corresponding to the types of objects, referred to as <strong>bookmark items</strong>, in the Bookmarks database in Firefox</li> - <li>две дополнительные функции, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#save(bookmarkItems.2C_options)"><code>save()</code></a> для создания, обновения и удаления закладок, и <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#search(queries.2C_options)"><code>search()</code></a> для получения закладок соответствующих параметрам запроса.</li> -</ul> - -<p><code>save()</code> и <code>search()</code> асинхронные функции: they synchronously return a <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#PlacesEmitter"><code>PlacesEmitter</code></a> object, which then asynchronously emits events as the operation progresses and completes.</p> - -<p>Each retrieved bookmark item represents only a snapshot of state at a specific time. The module does not automatically sync up a <code>Bookmark</code> instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user.</p> - -<h3 id="Примеры">Примеры</h3> - -<h4 id="Создание_новой_закладки">Создание новой закладки</h4> - -<pre class="brush: js">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` -});</pre> - -<h4 id="Создание_нескольких_закладок_в_группе">Создание нескольких закладок в группе</h4> - -<pre class="brush: js">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" -});</pre> - -<h4 id="Поиск_закладок">Поиск закладок</h4> - -<p>Bookmarks can be queried with the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#search(queries.2C_options)"><code>search()</code></a> 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.</p> - -<pre class="brush: js">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 -});</pre> - -<h2 id="Globals">Globals</h2> - -<h3 id="Constructors">Constructors</h3> - -<h4 class="addon-sdk-api-name" id="Bookmark(options)"><code>Bookmark(options)</code></h4> - -<p>Creates an unsaved bookmark instance.</p> - -<h5 id="Parameters">Parameters</h5> - -<p><strong>options : object</strong><br> - Required options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>title</td> - <td>string</td> - <td> - <p>The title for the bookmark. Required.</p> - </td> - </tr> - <tr> - <td>url</td> - <td>string</td> - <td> - <p>The URL for the bookmark. Required.</p> - </td> - </tr> - </tbody> -</table> - -<p>Optional options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>group</td> - <td>Group</td> - <td> - <p>The parent group that the bookmark lives under. Defaults to the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#UNSORTED">Bookmarks.UNSORTED</a> group.</p> - </td> - </tr> - <tr> - <td>index</td> - <td>number</td> - <td> - <p>The index of the bookmark within its group. Last item within the group by default.</p> - </td> - </tr> - <tr> - <td>tags</td> - <td>set</td> - <td> - <p>A set of tags to be applied to the bookmark.</p> - </td> - </tr> - </tbody> -</table> - -<h4 class="addon-sdk-api-name" id="Group(options)"><code>Group(options)</code></h4> - -<p>Creates an unsaved bookmark group instance.</p> - -<h5 id="Parameters_2">Parameters</h5> - -<p><strong>options : object</strong><br> - Required options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>title</td> - <td>string</td> - <td> - <p>The title for the group. Required.</p> - </td> - </tr> - </tbody> -</table> - -<p>Optional options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>group</td> - <td>Group</td> - <td> - <p>The parent group that the bookmark group lives under. Defaults to the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#UNSORTED">Bookmarks.UNSORTED</a> group.</p> - </td> - </tr> - <tr> - <td>index</td> - <td>number</td> - <td> - <p>The index of the bookmark group within its parent group. Last item within the group by default.</p> - </td> - </tr> - </tbody> -</table> - -<h4 class="addon-sdk-api-name" id="Separator(options)"><code>Separator(options)</code></h4> - -<p>Creates an unsaved bookmark separator instance.</p> - -<h5 id="Parameters_3">Parameters</h5> - -<p><strong>options : object</strong><br> - Optional options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>group</td> - <td>Group</td> - <td> - <p>The parent group that the bookmark group lives under. Defaults to the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#UNSORTED">Bookmarks.UNSORTED</a> group.</p> - </td> - </tr> - <tr> - <td>index</td> - <td>number</td> - <td> - <p>The index of the bookmark group within its parent group. Last item within the group by default.</p> - </td> - </tr> - </tbody> -</table> - -<h3 id="Functions">Functions</h3> - -<h4 class="addon-sdk-api-name" id="save(bookmarkItems_options)"><code>save(bookmarkItems, options)</code></h4> - -<p>Creating, saving, and deleting bookmarks are all done with the <code>save()</code> function. This function takes in any of:</p> - -<ul> - <li>a bookmark item (Bookmark, Group, Separator)</li> - <li>a duck-typed object (the relative properties for a bookmark item, in addition to a <code>type</code> property of <code>'bookmark'</code>, <code>'group'</code>, or <code>'separator'</code>)</li> - <li>an array of bookmark items.</li> -</ul> - -<p>All of the items passed in are pushed to the platform and are either created, updated or deleted.</p> - -<ul> - <li>adding items: if passing in freshly instantiated bookmark items or a duck-typed object, the item is created on the platform.</li> - <li>updating items: for an item referenced from a previous <code>save()</code> or from the result of a <code>search()</code> query, changing the properties and calling <code>save()</code> will update the item on the server.</li> - <li>deleting items: to delete a bookmark item, pass in a bookmark item with a property <code>remove</code> set to <code>true</code>.</li> -</ul> - -<p>The function returns a <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#PlacesEmitter"><code>PlacesEmitter</code></a> that emits a <code>data</code> event for each item as it is saved, and an <code>end</code> event when all items have been saved.</p> - -<pre class="brush: js">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. -});</pre> - -<h5 id="Parameters_4">Parameters</h5> - -<p><strong>bookmarkItems : bookmark|group|separator|array</strong><br> - A bookmark item (<a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Bookmark">Bookmark</a>, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Group">Group</a>, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Separator">Separator</a>), or an array of bookmark items to be saved.</p> - -<p><strong>options : object</strong><br> - Optional options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>resolve</td> - <td>function</td> - <td> - <p>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, <code>mine</code> and <code>platform</code>, where <code>mine</code> is the item that is being saved, and <code>platform</code> 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.</p> - </td> - </tr> - </tbody> -</table> - -<h5 id="Returns">Returns</h5> - -<p><strong>PlacesEmitter</strong> : Returns a <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#PlacesEmitter">PlacesEmitter</a>.</p> - -<h4 class="addon-sdk-api-name" id="remove(items)"><code>remove(items)</code></h4> - -<p>A helper function that takes in a bookmark item, or an <code>Array</code> of several bookmark items, and sets each item's <code>remove</code> property to true. This does not remove the bookmark item from the database: it must be subsequently saved.</p> - -<pre class="brush: js">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! - }); -})</pre> - -<h5 id="Parameters_5">Parameters</h5> - -<p><strong>items : Bookmark|Group|Separator|array</strong><br> - A bookmark item, or <code>Array</code> of bookmark items to be transformed to set their <code>remove</code> property to <code>true</code>.</p> - -<h5 id="Returns_2">Returns</h5> - -<p><strong>array</strong> : An array of the transformed bookmark items.</p> - -<h4 class="addon-sdk-api-name" id="search(queries_options)"><code>search(queries, options)</code></h4> - -<p>Queries can be performed on bookmark items by passing in one or more query objects, each of which is given one or more properties.</p> - -<p>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.</p> - -<p>For example, suppose we called <code>search()</code> with two query objects:</p> - -<pre class="brush: js">[{ url: "mozilla.org", tags: ["mobile"]}, -{ tags: ["firefox-os"]}]</pre> - -<p>This will return:</p> - -<ul> - <li>all bookmark items from mozilla.org that are also tagged "mobile"</li> - <li>all bookmark items that are tagged "firefox-os"</li> -</ul> - -<p>An <code>options</code> object may be used to determine overall settings such as sort order and how many objects should be returned.</p> - -<h5 id="Parameters_6">Parameters</h5> - -<p><strong>queries : object|array</strong><br> - An <code>Object</code> representing a query, or an <code>Array</code> of <code>Objects</code> 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.</p> - -<p><strong>options : object</strong><br> - Optional options:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Name</th> - <th scope="col">Type</th> - <th scope="col"> </th> - </tr> - </thead> - <tbody> - <tr> - <td>count</td> - <td>number</td> - <td> - <p>The number of bookmark items to return. If left undefined, no limit is set.</p> - </td> - </tr> - <tr> - <td>sort</td> - <td>string</td> - <td> - <p>A string specifying how the results should be sorted. Possible options are <code>'title'</code>, <code>'date'</code>, <code>'url'</code>, <code>'visitCount'</code>, <code>'dateAdded'</code> and <code>'lastModified'</code>.</p> - </td> - </tr> - <tr> - <td>descending</td> - <td>boolean</td> - <td> - <p>A boolean specifying whether the results should be in descending order. By default, results are in ascending order.</p> - </td> - </tr> - </tbody> -</table> - -<h3 id="Properties">Properties</h3> - -<h4 class="addon-sdk-api-name" id="MENU"><code>MENU</code></h4> - -<p>This is a constant, default <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Group"><code>Group</code></a> on the Firefox platform, the <strong>Bookmarks Menu</strong>. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.</p> - -<h4 class="addon-sdk-api-name" id="TOOLBAR"><code>TOOLBAR</code></h4> - -<p>This is a constant, default <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Group"><code>Group</code></a> on the Firefox platform, the <strong>Bookmarks Toolbar</strong>. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.</p> - -<h4 class="addon-sdk-api-name" id="UNSORTED"><code>UNSORTED</code></h4> - -<p>This is a constant, default <a href="/en-US/Add-ons/SDK/Low-Level_APIs/places_bookmarks#Group"><code>Group</code></a> on the Firefox platform, the <strong>Unsorted Bookmarks</strong> group. It can be used in queries or specifying the parent of a bookmark item, but it cannot be modified.</p> - -<h2 id="Bookmark">Bookmark</h2> - -<h3 id="Properties_2">Properties</h3> - -<h4 class="addon-sdk-api-name" id="title"><code>title</code></h4> - -<p>The bookmark's title.</p> - -<h4 class="addon-sdk-api-name" id="url"><code>url</code></h4> - -<p>The bookmark's URL.</p> - -<h4 class="addon-sdk-api-name" id="group"><code>group</code></h4> - -<p>The group instance that the bookmark lives under.</p> - -<h4 class="addon-sdk-api-name" id="index"><code>index</code></h4> - -<p>The index of the bookmark within its group.</p> - -<h4 class="addon-sdk-api-name" id="updated"><code>updated</code></h4> - -<p>A Unix timestamp indicating when the bookmark was last updated on the platform.</p> - -<h4 class="addon-sdk-api-name" id="tags"><code>tags</code></h4> - -<p>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a> of tags that the bookmark is tagged with.</p> - -<h2 id="Group">Group</h2> - -<h3 id="Properties_3">Properties</h3> - -<h4 class="addon-sdk-api-name" id="title_2"><code>title</code></h4> - -<p>The bookmark group's title.</p> - -<h4 class="addon-sdk-api-name" id="group_2"><code>group</code></h4> - -<p>The group instance that the bookmark group lives under.</p> - -<h4 class="addon-sdk-api-name" id="index_2"><code>index</code></h4> - -<p>The index of the bookmark group within its group.</p> - -<h4 class="addon-sdk-api-name" id="updated_2"><code>updated</code></h4> - -<p>A Unix timestamp indicating when the bookmark was last updated on the platform.</p> - -<h2 id="Separator">Separator</h2> - -<h3 id="Properties_4">Properties</h3> - -<h4 class="addon-sdk-api-name" id="group_3"><code>group</code></h4> - -<p>The group instance that the bookmark group lives under.</p> - -<h4 class="addon-sdk-api-name" id="index_3"><code>index</code></h4> - -<p>The index of the bookmark group within its group.</p> - -<h4 class="addon-sdk-api-name" id="updated_3"><code>updated</code></h4> - -<p>A Unix timestamp indicating when the bookmark was last updated on the platform.</p> - -<h2 id="PlacesEmitter">PlacesEmitter</h2> - -<p>The <code>PlacesEmitter</code> is not exported from the module, but returned from the <code>save</code> and <code>search</code> functions. The <code>PlacesEmitter</code> inherits from <a href="/en-US/Add-ons/SDK/Low-Level_APIs/event_target"><code>event/target</code></a>, and emits <code>data</code>, <code>error</code>, and <code>end</code>.</p> - -<p><code>data</code> events are emitted for every individual operation (such as: each item saved, or each item found by a search query), whereas <code>end</code> events are emitted as the aggregate of an operation, passing an array of objects into the handler.</p> - -<h3 id="Events">Events</h3> - -<h4 class="addon-sdk-api-name" id="data"><code>data</code></h4> - -<p>The <code>data</code> event is emitted when a bookmark item that was passed into the <code>save</code> 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 <code>data</code> event.</p> - -<pre class="brush: js">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 -});</pre> - -<p>The <code>data</code> event is also called for <code>search</code> requests, with each result being passed individually into its own <code>data</code> event.</p> - -<pre class="brush: js">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 -});</pre> - -<h5 id="Arguments">Arguments</h5> - -<p><strong>Bookmark|Group|Separator</strong> : For the <code>save</code> function, this is the saved, latest snapshot of the bookmark item. For <code>search</code>, this is a snapshot of a bookmark returned from the search query.</p> - -<p><strong>Bookmark|Group|Separator|object</strong> : Only in <code>save</code> data events. The initial instance of the item that was used for the save request.</p> - -<h4 class="addon-sdk-api-name" id="error"><code>error</code></h4> - -<p>The <code>error</code> event is emitted whenever a bookmark item's save could not be completed.</p> - -<h5 id="Arguments_2">Arguments</h5> - -<p><strong>string</strong> : A string indicating the error that occurred.</p> - -<p><strong>Bookmark|Group|Separator|object</strong> : Only in <code>save</code> error events. The initial instance of the item that was used for the save request.</p> - -<h4 class="addon-sdk-api-name" id="end"><code>end</code></h4> - -<p>The <code>end</code> event is called when all bookmark items and dependencies have been saved, or an aggregate of all items returned from a search query.</p> - -<h5 id="Arguments_3">Arguments</h5> - -<p><strong>array</strong> : The array is an ordered list of the input bookmark items, replaced with their updated, latest snapshot instances (the first argument in the <code>data</code> 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 <code>data</code> or <code>error</code> handler).</p> diff --git a/files/ru/mozilla/add-ons/sdk/tools/console/index.html b/files/ru/mozilla/add-ons/sdk/tools/console/index.html deleted file mode 100644 index d28b31d127..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/console/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: console -slug: Mozilla/Add-ons/SDK/Tools/console -translation_of: Archive/Add-ons/Add-on_SDK/Tools/console ---- -<p><span class="seoSummary">Enables your add-on to log error, warning or informational messages.</span> If you have started Firefox for your add-on from the command line with <code>cfx run</code> or <code>cfx test</code> 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 <a href="/en-US/docs/Tools/Browser_Console">Browser Console</a>.</p> -<p>If you're developing your add-on using the <a href="https://addons.mozilla.org/en-US/firefox/addon/autoinstaller/">Extension Auto-installer</a>, then the add-on is installed in Firefox, meaning that messages will appear in the Browser Console. But see the discussion of <a href="/en-US/Add-ons/SDK/Tools/console#Logging_Levels">logging levels</a>: by default, messages logged using <code>log()</code>, <code>info()</code>, <code>trace()</code>, or <code>warn()</code> won't be logged in these situations.</p> -<h2 id="Console_Methods">Console Methods</h2> -<p>All console methods except <code>exception()</code> and <code>trace()</code> 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.</p> -<h3 id="console.debug(object_object_...)"><code>console.debug(<em>object</em>[, <em>object</em>, ...])</code></h3> -<p>Logs the arguments to the console, preceded by "debug:" and the name of your add-on:</p> -<pre class="brush: js">console.debug("This is a debug message");</pre> -<pre>debug: my-addon: This is a debug message -</pre> -<h3 id="console.error(object_object_...)"><code>console.error(<em>object</em>[, <em>object</em>, ...])</code></h3> -<p>Logs the arguments to the console, preceded by "error:" and the name of your add-on:<code> </code></p> -<pre class="brush: js">console.error("This is an error message");</pre> -<pre>error: my-addon: This is an error message -</pre> -<h3 id="console.exception(exception)"><code>console.exception(<em>exception</em>)</code></h3> -<p>Logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available.</p> -<pre class="brush: js">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!"); -}</pre> -<pre>error: my-addon: An exception occurred. -UserException: Thing could not be done! -</pre> -<h3 id="console.info(object_object_...)"><code>console.info(<em>object</em>[, <em>object</em>, ...])</code></h3> -<p>A synonym for <code>console.log()</code>.</p> -<h3 id="console.log(object_object_...)"><code>console.log(<em>object</em>[, <em>object</em>, ...])</code></h3> -<p>Logs the arguments to the console, preceded by "info:" and the name of your add-on:</p> -<pre class="brush: js">console.log("This is an informational message");</pre> -<pre>info: my-addon: This is an informational message -</pre> -<h3 id="console.time(name)"><code>console.time(name)</code></h3> -<p>Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.</p> -<h3 id="console.timeEnd(name)"><code>console.timeEnd(name)</code></h3> -<p>Stops the specified timer and logs the elapsed time in seconds since its start. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/console#Timers">Timers</a>.</p> -<h3 id="console.trace()"><code>console.trace()</code></h3> -<p>Logs a stack trace at the point the function is called.</p> -<h3 id="console.warn(object_object_...)"><code>console.warn(<em>object</em>[, <em>object</em>, ...])</code></h3> -<p>Logs the arguments to the console, preceded by "warn:" and the name of your add-on:<code> </code></p> -<pre class="brush: js"><code>console.warn("This is a warning message");</code></pre> -<pre>warn: my-addon: This is a warning message -</pre> -<h2 id="Logging_Levels">Logging Levels</h2> -<p>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.</p> -<p>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.</p> -<p>At a given logging level, only calls to the corresponding functions and functions with a higher severity will have any effect.</p> -<p>For example, if the logging level is set to "info", then calls to <code>info()</code>, <code>log()</code>, <code>warn()</code>, and <code>error()</code> will all result in output being written. But if the logging level is "warn" then only calls to <code>warn()</code> and <code>error()</code> have any effect, and calls to <code>info()</code> and <code>log()</code> are simply discarded.</p> -<p>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.</p> -<p>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:</p> -<table class="standard-table"> - <tbody> - <tr> - <th>Level</th> - <th>Will log calls to:</th> - </tr> - <tr> - <td>all</td> - <td>Any console method</td> - </tr> - <tr> - <td>debug</td> - <td><code>debug(), error(), exception(), info(), log(), time(), timeEnd(), trace(), warn()</code></td> - </tr> - <tr> - <td>info</td> - <td><code>error(), exception(), info(), log(), time(), timeEnd(), trace(), warn()</code></td> - </tr> - <tr> - <td>warn</td> - <td><code>error(), exception(), warn()</code></td> - </tr> - <tr> - <td>error</td> - <td><code>error(), exception()</code></td> - </tr> - <tr> - <td>off</td> - <td>Nothing</td> - </tr> - </tbody> -</table> -<h3 id="Setting_the_Logging_Level">Setting the Logging Level</h3> -<p>The logging level defaults to "error".</p> -<p>There are two system preferences that can be used to override this default:</p> -<ul> - <li> - <p><strong>extensions.sdk.console.logLevel</strong>: if set, this determines the logging level for all installed SDK-based add-ons.</p> - </li> - <li> - <p><strong>extensions.</strong><em>extensionID</em><strong>.sdk.console.logLevel</strong>, where <em>extensionID</em> is an add-on's <a href="/en-US/Add-ons/SDK/Guides/Program_ID">Program ID</a>. If set, this determines the logging level for the specified add-on. This overrides the global preference if both preferences are set.</p> - </li> -</ul> -<p>Both these preferences can be set programmatically using the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/preferences_service"><code>preferences/service</code></a> API, or manually using <a href="http://kb.mozillazine.org/About:config">about:config</a>. The value for each preference is the desired logging level, given as a string.</p> -<p>When you run your add-on using <code>cfx run</code> or <code>cfx test</code>, the global <strong>extensions.sdk.console.logLevel</strong> preference is automatically set to "info". This means that calls to <code>console.log()</code> will appear in the console output.</p> -<p>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 <code>debug()</code>, <code>log()</code>, <code>info()</code>, <code>trace()</code>, and <code>warn()</code> will not appear in the console.</p> -<p>This includes add-ons being developed using the <a href="https://addons.mozilla.org/en-US/firefox/addon/autoinstaller/">Extension Auto-installer</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tools/index.html b/files/ru/mozilla/add-ons/sdk/tools/index.html deleted file mode 100644 index b55c672f17..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Tools -slug: Mozilla/Add-ons/SDK/Tools -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Tools ---- -<p>Articles listed here provide a reference for the SDK's tools:</p> -<p>{{ LandingPageListSubpages ("/en-US/Add-ons/SDK/Tools", 5) }}</p> diff --git a/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html b/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html deleted file mode 100644 index dbfacde500..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tools/jpm/index.html +++ /dev/null @@ -1,497 +0,0 @@ ---- -title: jpm -slug: Mozilla/Add-ons/SDK/Tools/jpm -translation_of: Archive/Add-ons/Add-on_SDK/Tools/jpm ---- -<div class="note"> -<p>Вы можете использовать <code>jpm</code> для Firefox 38 или более поздних версий.</p> - -<p>Данный материал относится только для jpm.</p> -</div> - -<p><span class="seoSummary">Это Node-ориентированная замена устаревшего <a href="/en-US/Add-ons/SDK/Tools/cfx">cfx</a>. Позволяет тестировать, запускать и создавать дополнения для Firefox.</span></p> - -<p>Смотри также <a href="/en-US/Add-ons/SDK/Tutorials/Getting_Started_%28jpm%29">jpm tutorial</a>.</p> - -<p>jpm вызывается через:</p> - -<pre class="brush: bash">jpm [command] [options] -</pre> - -<p>jpm поддерживает следующие глобальные опции:</p> - -<pre class="brush: bash">-h, --help - show a help message and exit --V, --version - print the jpm version number -</pre> - -<h2 id="Установка">Установка</h2> - -<p>jpm распространяется с помощью менеджера пакетов <a class="external external-icon" href="https://www.npmjs.org/package/jpm">npm</a>, поэтому чтобы установить jpm, вам необходимо предварительно установить менеджер пакетов npm, если вы этого ещё не сделали. npm входит в Node.js, поэтому чтобы установить npm - посетите <a class="external external-icon" href="http://nodejs.org/">nodejs.org</a> и нажмите кнопку INSTALL.</p> - -<p>После этого вы можете установить jpm, как и любой другой npm пакет:</p> - -<pre>npm install jpm -g</pre> - -<p>В зависимости от настроек и операционной системы, вам может потребоваться запустить его с правами администратора (Linux: Debian, Ubuntu, и т.п.):</p> - -<pre class="brush: bash">sudo npm install jpm -g</pre> - -<p>После установки введите в командной строке:</p> - -<pre class="brush: bash">jpm</pre> - -<p>Вы должны увидеть краткое описание доступных команд. Обратите внимание, что в отличие от cfx, jpm доступно из любой запущенной командной строки, в случае, если при установке jpm использовался флаг -g.</p> - -<h3 id="Проблемы">Проблемы?</h3> - -<p>Если у вас возникли проблемы, то обратитесь за помощью. Пользователи SDK и участники проекта готовы обсудить и предложения в <a class="external external-icon" href="http://groups.google.com/group/mozilla-labs-jetpack/topics">project mailing list</a>. Попробуйте поискать там, возможно похожий вопрос уже обсуждался там. Вы также можете обратиться к пользователям SDK в <a class="external external-icon" href="http://mibbit.com/?channel=%23jetpack&server=irc.mozilla.org">#jetpack</a> на <a class="external external-icon" href="http://irc.mozilla.org/">Mozilla's IRC network</a>.</p> - -<h2 id="Справочник_команд">Справочник команд</h2> - -<p>В jpm доступно шесть команд:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td style="width: 20%;"><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_init"><code>jpm init</code></a></td> - <td>Создать каркас дополнения в качестве отправной точки для создания вашего дополнения.</td> - </tr> - <tr> - <td><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_run"><code>jpm run</code></a></td> - <td>Запустить копию Firefox с установленным дополнением.</td> - </tr> - <tr> - <td><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_test"><code>jpm test</code></a></td> - <td>Запуск тестирования модуля вашего дополнения.</td> - </tr> - <tr> - <td><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_xpi"><code>jpm xpi</code></a></td> - <td>Упаковать дополнение в <a href="https://developer.mozilla.org/en/XPI">XPI</a> пакет, формат файла установки для дополнений Firefox.</td> - </tr> - <tr> - <td><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_post"><code>jpm post</code></a></td> - <td>Упаковать дополнение в пакет <a href="https://developer.mozilla.org/en/XPI">XPI</a> и отправить на URL.</td> - </tr> - <tr> - <td><a href="/en-US/Add-ons/SDK/Tools/jpm#jpm_watchpost"><code>jpm watchpost</code></a></td> - <td>Упаковывать дополнение в пакет <a href="https://developer.mozilla.org/en/XPI">XPI</a> и отправлять на URL при каждом изменении файла.</td> - </tr> - </tbody> -</table> - -<h3 id="jpm_init">jpm init</h3> - -<p>Данная команда инициализирует новое дополнение, с нуля.</p> - -<p>Для этого создайте новый каталог, перейдите в него и запустите <code>jpm init</code>.</p> - -<pre class="brush: bash">mkdir my-addon -cd my-addon -jpm init</pre> - -<p>Вам будет предложено указать некоторую информацию о вашем дополнении: данная информация будет использована для создания файла настроек дополнения <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json">package.json</a>.</p> - -<ul> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#title">title</a></li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#name">name</a>: По умолчанию это имя каталога, в котором была запущена команда jpm init. За исключнием случаев, когда заполненно поле <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#id"><code>id</code></a> в файле package.json, тогда jpm добавит указатель "@" перед именем и использует в качестве него значение поля <a href="https://developer.mozilla.org/en-US/Add-ons/Install_Manifests#id"><code>id</code> field in the add-on's install manifest</a>.</li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#version">version</a></li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#description">description</a></li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#main">entry point</a> (which maps to "main" in package.json)</li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#author">author</a></li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#engines">engines</a> (supported applications)</li> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json#license">license</a></li> -</ul> - -<p>Большинство из этих полей имеют значения по умолчанию, который указан в скобках после вопроса. Если вы просто нажмите Enter, то в настройках будет указано значение по умолчанию.</p> - -<p>После того как вы укажете значения или выберите значение по умолчанию для этих свойств, вам будет показано полное содержание "package.json" и предложено принять его.</p> - -<p>После jpm создаст каркас дополнения в качестве отправной точки для разрабатываемого вами дополнения, со следующей структурой файлов:</p> - -<ul class="directory-tree"> - <li>my-addon - <ul> - <li>index.js</li> - <li>package.json</li> - <li>test - <ul> - <li>test-index.js</li> - </ul> - </li> - </ul> - </li> -</ul> - -<h3 id="jpm_run">jpm run</h3> - -<p>Эта команда запускает новый экземпляр Firefox с подключенным дополнением:</p> - -<pre class="brush: bash">jpm run</pre> - -<p><code>jpm run</code> принимает следующие значения:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td style="width: 30%;"><code>-b --binary BINARY</code></td> - <td> - <p>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.</p> - - <pre class="brush: bash"> -jpm run -b /path/to/Firefox/Nightly</pre> - See <a href="/en-US/Add-ons/SDK/Tools/jpm#Selecting_a_browser_version">Selecting a browser version</a>.</td> - </tr> - <tr> - <td><code>--binary-args CMDARGS</code></td> - <td> - <p>Pass <a href="/en-US/docs/Mozilla/Command_Line_Options">extra arguments</a> to Firefox.</p> - - <p>For example, to pass the <code>-jsconsole</code> argument to Firefox, which will launch the <a href="/en-US/docs/Tools/Browser_Console">Browser Console</a>, try the following:</p> - - <pre class="brush: bash"> -jpm run --binary-args -jsconsole</pre> - - <p>To pass multiple arguments, or arguments containing spaces, quote them:</p> - - <pre class="brush: bash"> -jpm run --binary-args '-url mzl.la -jsconsole'</pre> - </td> - </tr> - <tr> - <td><code>--debug</code></td> - <td>Run the <a href="/en-US/Add-ons/Add-on_Debugger">add-on debugger</a> attached to the add-on.</td> - </tr> - <tr> - <td><code>-o --overload PATH</code></td> - <td> - <p>Rather than use the SDK modules built into Firefox, use the modules found at PATH. If <code>-o</code> is specified and PATH is omitted, jpm will look for the JETPACK_ROOT environment variable and use its value as the path.</p> - - <p>See <a href="/en-US/Add-ons/SDK/Tools/jpm#Overloading_the_built-in_modules">Overloading the built-in modules</a> for more information.</p> - </td> - </tr> - <tr> - <td><code>-p --profile=<code> PROFILE</code></code></td> - <td> - <p>By default, jpm uses a clean temporary Firefox <a href="http://support.mozilla.com/en-US/kb/profiles">profile</a> each time you call jpm run. Use the <code>--profile</code> option to instruct jpm to launch Firefox with an existing profile.</p> - - <p>The PROFILE value may be a profile name or the path to the profile.</p> - - <p>See <a href="/en-US/Add-ons/SDK/Tools/jpm#Using_profiles">Using profiles</a> for more information.</p> - </td> - </tr> - <tr> - <td><code>-v --verbose</code></td> - <td>Verbose operation.</td> - </tr> - <tr> - <td><code>--no-copy</code></td> - <td> - <div class="warning">Use with caution because <code>jpm run|test</code> changes many preferences, never use with your main profile.</div> - - <div class="note">This only applies when <code>--profile</code> is used.</div> - Disables the copying of the profile used, which allows one to reuse a profile.</td> - <td> </td> - </tr> - </tbody> -</table> - -<h3 id="jpm_test">jpm test</h3> - -<p>Команда запускает тестирование дополнения. Происходит следующее:</p> - -<ul> - <li>Обзор каталога с именем "test" в корневом каталоге дополнения</li> - <li>Открывается каждый файл, имя которого начинается с "test-" в этом каталоге (обратите внимание на дефис после слова "test" в имени jpm файла - в тест будет включён файл вида "test-myCode.js", но исключены файлы вида "test_myCode.js" или "testMyCode.js"</li> - <li>Вызываются все функции, извлечённые из файла, имя которого начинается с "test"</li> -</ul> - -<pre class="brush: bash">jpm test -</pre> - -<p>See the <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Unit_testing">tutorial on unit testing</a> and the <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/test_assert">reference documentation for the <code>assert</code> module</a> for more details on this.</p> - -<p><code>jpm test</code> accepts the following options:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td><code>-b --binary BINARY</code></td> - <td> - <p>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.</p> - - <pre class="brush: bash"> -jpm test -b /path/to/Firefox/Nightly</pre> - - <p>See <a href="/en-US/Add-ons/SDK/Tools/jpm#Selecting_a_browser_version">Selecting a browser version</a>.</p> - </td> - </tr> - <tr> - <td><code>--binary-args CMDARGS</code></td> - <td> - <p>Pass <a href="http://kb.mozillazine.org/Command_line_arguments">extra arguments</a> to Firefox.</p> - - <p>For example, to pass the <code>-jsconsole</code> argument to Firefox, which will launch the <a href="/en-US/docs/Tools/Browser_Console">Browser Console</a>, try the following:</p> - - <pre class="brush: bash"> -jpm test --binary-args -jsconsole</pre> - - <p>To pass multiple arguments, or arguments containing spaces, quote them:</p> - - <pre class="brush: bash"> -jpm test --binary-args '-url mzl.la -jsconsole'</pre> - </td> - </tr> - <tr> - <td><code>--debug</code></td> - <td>Run the <a href="/en-US/Add-ons/Add-on_Debugger">add-on debugger</a> attached to the add-on.</td> - </tr> - <tr> - <td style="width: 30%;"><code>-f --filter FILE[:TEST]</code></td> - <td> - <p>Only run tests whose filenames match FILE and optionally match TEST, both regexps.</p> - - <pre class="brush: bash"> -jpm test --filter base64:btoa</pre> - - <p>The above command only runs tests in files whose names contain "base64", and in those files only runs tests whose names contain "btoa".</p> - </td> - </tr> - <tr> - <td style="width: 30%;"><code>-o --overload PATH</code></td> - <td> - <p>Rather than use the SDK modules built into Firefox, use the modules found at PATH. If <code>-o</code> is specified and PATH is omitted, jpm will look for the JETPACK_ROOT environment variable and use its value as the path.</p> - - <p>See <a href="/en-US/Add-ons/SDK/Tools/jpm#Overloading_the_built-in_modules">Overloading the built-in modules</a> for more information.</p> - </td> - </tr> - <tr> - <td style="width: 30%;"><code>-p --profile<code> PROFILE</code></code></td> - <td> - <p>By default, jpm uses a clean temporary Firefox <a href="http://support.mozilla.com/en-US/kb/profiles">profile</a> each time you call jpm run. Use the <code>--profile</code> option to instruct jpm to launch Firefox with an existing profile.</p> - - <p>The PROFILE value may be a profile name or the path to the profile.</p> - - <p>See <a href="/en-US/Add-ons/SDK/Tools/jpm#Using_profiles">Using profiles</a> for more information.</p> - </td> - </tr> - <tr> - <td><code>--stop-on-error</code></td> - <td> - <p>By default jpm test keeps running tests even after tests fail. Specify <code>--stop-on-error</code> to stop running tests after the first failure:</p> - - <pre class="brush: bash"> -jpm test --stop-on-error</pre> - </td> - </tr> - <tr> - <td><code>--tbpl</code></td> - <td>Print test output in <a href="https://treeherder.mozilla.org/">Treeherder</a> format</td> - </tr> - <tr> - <td><code>--times NUMBER</code></td> - <td> - <p>Run tests NUMBER of times:</p> - - <pre class="brush: bash"> -jpm test --times 2</pre> - </td> - </tr> - <tr> - <td><code>-v --verbose</code></td> - <td>Verbose operation.</td> - </tr> - <tr> - <td><code>--no-copy</code></td> - <td> - <div class="warning">Use with caution because <code>jpm run|test</code> changes many preferences, never use with your main profile.</div> - - <div class="note">This only applies when <code>--profile</code> is used.</div> - Disables the copying of the profile used, which allows one to reuse a profile.</td> - </tr> - </tbody> -</table> - -<h3 id="jpm_xpi">jpm xpi</h3> - -<p>Эта команда собирает дополнение в пакет XPI. Это формат дополнений, которые можно легко установить Mozilla.</p> - -<pre class="brush: bash">jpm xpi</pre> - -<p>It looks for a file called <code>package.json</code> 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.</p> - -<p>Once you have built an XPI file you can distribute your add-on by submitting it to <a href="http://addons.mozilla.org">addons.mozilla.org</a>.</p> - -<p><code>jpm xpi</code> accepts the following option:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td><code>-v --verbose</code></td> - <td> - <p>Verbose operation:</p> - - <pre class="brush: bash"> -jpm xpi -v</pre> - </td> - </tr> - </tbody> -</table> - -<h3 id="jpm_post">jpm post</h3> - -<p>This command packages the add-on as an <a href="https://developer.mozilla.org/en/XPI">XPI</a> file, the posts it to some url.</p> - -<pre class="brush: bash">jpm post</pre> - -<p>It looks for a file called <code>package.json</code> in the current directory and creates a XPI file with which to post to the <code>--post-url</code>.</p> - -<p><code>jpm post</code> accepts the following options:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td><code>--post-url URL</code></td> - <td> - <p>The url to post the extension to after creating a XPI.</p> - - <pre class="brush: bash"> -jpm post --post-url http://localhost:8888/</pre> - - <p>See <a href="https://www.npmjs.com/package/jpm#using-post-and-watchpost">Using Post and Watchpost</a> for more information.</p> - </td> - </tr> - <tr> - <td><code>-v --verbose</code></td> - <td> - <p>Verbose operation:</p> - - <pre class="brush: bash"> -jpm post --post-url http://localhost:8888/ -v</pre> - </td> - </tr> - </tbody> -</table> - -<h3 id="jpm_watchpost">jpm watchpost</h3> - -<p>This command packages the add-on as an <a href="https://developer.mozilla.org/en/XPI">XPI</a> file, the posts it to some url whenever a file in the current working directory changes.</p> - -<pre class="brush: bash">jpm watchpost</pre> - -<p>Creates a XPI whenever a file in the current working directory changes and posts that to the <code>--post-url</code>.</p> - -<p><code>jpm watchpost</code> accepts the following options:</p> - -<table class="fullwidth-table standard-table"> - <tbody> - <tr> - <td><code>--post-url URL</code></td> - <td> - <p>The url to post the extension to after creating a XPI.</p> - - <pre class="brush: bash"> -jpm watchpost --post-url http://localhost:8888/</pre> - - <p>See <a href="https://www.npmjs.com/package/jpm#using-post-and-watchpost">Using Post and Watchpost</a> for more information.</p> - </td> - </tr> - <tr> - <td><code>-v --verbose</code></td> - <td> - <p>Verbose operation:</p> - - <pre class="brush: bash"> -jpm watchpost --post-url http://localhost:8888/ -v</pre> - </td> - </tr> - </tbody> -</table> - -<h2 id="Techniques">Techniques</h2> - -<h3 id="Selecting_a_browser_version">Selecting a browser version</h3> - -<p>By default, <code>jpm run</code> and <code>jpm test</code> will run the release version of Firefox. You can instruct jpm to use a different version in one of two ways:</p> - -<ul> - <li> - <p>you can use the <code>-b</code> or <code>--binary</code> option to instruct jpm to run a different version of Firefox. You can supply a path to a specific binary:</p> - - <pre class="brush: bash">jpm run -b /path/to/Firefox/Nightly</pre> - - <p>As a shorthand for this, you can pass "nightly", "aurora", "beta", or "firefox" and jpm will look in the default location for these Firefox versions:</p> - - <pre class="brush: bash">jpm run -b nightly</pre> - </li> - <li> - <p>you can set the <code>JPM_FIREFOX_BINARY</code> environment variable with the path to the version of Firefox you want to run. When you invoke <code>jpm run</code> or <code>jpm test</code> without the <code>-b</code> option, jpm will first check <code>JPM_FIREFOX_BINARY</code>, and use this as the path if it is set.</p> - </li> -</ul> - -<h3 id="Using_.jpmignore_to_ignore_files">Using <code>.jpmignore</code> to ignore files</h3> - -<p>Using <code>.jpmignore</code> is similar to using <code>.gitignore</code> with <code>git</code>, <code>.hgignore</code> with Mercurial, or <code>.npmignore</code> with <code>npm</code>. By using this file you can let <code>jpm</code> know which files you would like it to ignore when building a <code>.xpi</code> file with <code>jpm xpi</code>.</p> - -<p>Here is an example:</p> - -<pre class="brush: bash"># Ignore .DS_Store files created by mac -.DS_Store - -# Ignore any zip or xpi files -*.zip -*.xpi -</pre> - -<p>A <code>.jpmignore</code> file with the above contents would ignore all zip files and <code>.DS_Store</code> files from the xpi generated by <code>jpm xpi</code>.</p> - -<h3 id="Using_profiles_2"><a name="Using_profiles">Using profiles</a></h3> - -<p>By default, <code>jpm run</code> uses a new profile each time it is executed. This means that any profile-specific data entered from one run of <code>jpm</code> will not, by default, be available in the next run.</p> - -<p>This includes, for example, any extra add-ons you installed, or your history, or any data stored using the <a href="/en-US/Add-ons/SDK/High-Level_APIs/simple-storage">simple-storage</a> API.</p> - -<p>To make <code>jpm</code> use a specific profile, pass the <code>--profile</code> option, specifying the name of the profile you wish to use, or the path to the profile.</p> - -<pre class="brush: bash">jpm run --profile boogaloo -</pre> - -<pre class="brush: bash">jpm run --profile path/to/boogaloo</pre> - -<p>If you supply <code>--profile</code> but its argument is not the name of or path to an existing profile, jpm will open the <a href="https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles">profile manager</a>, enabling you to select and existing profile or create a new one:</p> - -<pre class="brush: bash">jpm run --profile i-dont-exist</pre> - -<h3 id="Developing_without_browser_restarts">Developing without browser restarts</h3> - -<p>Because <code>jpm run</code> 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 <a href="https://addons.mozilla.org/en-US/firefox/addon/autoinstaller/" rel="noreferrer">Extension Auto-Installer</a> 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:</p> - -<ul> - <li>make a change to your add-on</li> - <li>run <code>jpm post --post-url http://localhost:8888/</code>, to make a xpi and post it.</li> -</ul> - -<p>You could even automate this workflow with a simple script. For example:</p> - -<pre class="brush: bash">jpm watchpost --post-url http://localhost:8888/ -</pre> - -<p>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 <code>jpm run</code>. This means that if you want to see output from <a href="/en-US/Add-ons/SDK/Tutorials/Logging" rel="noreferrer"><code>console.log()</code></a> messages, you'll have to tweak a setting. See the documentation on <a href="/en-US/Add-ons/SDK/Tools/console#Logging_Levels" rel="noreferrer">logging levels</a> for the details on this.</p> - -<h3 id="Overloading_the_built-in_modules">Overloading the built-in modules</h3> - -<p>The SDK modules you use to implement your add-on are built into Firefox. When you run or package an add-on using <code>jpm run</code> or <code>jpm xpi</code>, the add-on will use the versions of the modules in the version of Firefox that hosts it.</p> - -<p>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:</p> - -<ul> - <li>get a local copy of the SDK modules that you want: this usually means checking out the SDK from its <a href="https://github.com/mozilla/addon-sdk" rel="noreferrer">GitHub repo</a></li> - <li>set the <code>JETPACK_ROOT</code> environment variable to your local copy</li> - <li>pass the <code>-o</code> option to <code>jpm run</code> or <code>jpm xpi</code>:</li> -</ul> - -<pre>jpm run -o -</pre> - -<p>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 <code>JETPACK_ROOT</code> environment variable, you can pass the location of your copy of the SDK modules along with <code>-o</code>:</p> - -<pre>jpm run -o "/path/to/SDK/"</pre> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html deleted file mode 100644 index d9453e9767..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Создание простого Add-on (jpm) -slug: Mozilla/Add-ons/SDK/Tutorials/Getting_Started_(jpm) -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Getting_Started_(jpm) ---- -<div class="note"> -<p>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 <a href="http://nodejs.org/">Node.js</a>. It replaces the old cfx tool.</p> - -<p>You can use jpm from Firefox 38 onwards.</p> - -<p>This article describes how to develop using jpm.</p> -</div> - -<p>This tutorial walks through creating a simple add-on using the SDK.</p> - -<h2 id="Prerequisites">Prerequisites</h2> - -<p>To create add-ons for Firefox using the SDK, you'll need:</p> - -<ul> - <li>Firefox version 38 or later. If you need to work with earlier versions of Firefox, you'll need to use the old cfx tool. See instructions for <a href="/en-US/Add-ons/SDK/Tutorials/Getting_started">getting started with cfx</a>.</li> - <li>the command-line jpm tool. See the instructions for <a href="/en-US/Add-ons/SDK/Tools/jpm#Installation">installing jpm</a>. Once you've done that, you'll be looking at a command prompt.</li> -</ul> - -<h2 id="Initializing_an_empty_add-on">Initializing an empty add-on</h2> - -<p>In the command prompt, create a new directory. Navigate to it, type <code>jpm init</code>, and hit enter:</p> - -<pre>mkdir my-addon -cd my-addon -jpm init -</pre> - -<p>You'll then be asked to supply some information about your add-on: this will be used to create your add-on's <a href="/en-US/Add-ons/SDK/Tools/package_json">package.json</a> file. For now, just press Enter to accept the default for each property. For more information on <code>jpm init</code>, see the <a href="/en-US/Add-ons/SDK/Tools/jpm#Command_reference">jpm command reference</a>.</p> - -<p>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.</p> - -<h2 id="Implementing_the_add-on">Implementing the add-on</h2> - -<p>Now you can write the add-on's code. Unless you've changed the value of "entry point" ("<a href="/en-US/Add-ons/SDK/Tools/package_json#main">main</a>" 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:</p> - -<pre class="brush: 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("http://www.mozilla.org/"); -} -</pre> - -<div class="note"> -<p>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.</p> - -<p>In cfx, the entry point defaults to "main.js", and is located in the "lib" directory under the add-on's root.</p> -</div> - -<p>Save the file.</p> - -<p>Next, create a directory called "data" in your add-on's root, and save these three icon files to the "data" directory:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7635/icon-16.png" style="height: 16px; width: 16px;"></td> - <td>icon-16.png</td> - </tr> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7637/icon-32.png" style="height: 32px; width: 32px;"></td> - <td>icon-32.png</td> - </tr> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7639/icon-64.png" style="height: 64px; width: 64px;"></td> - <td>icon-64.png</td> - </tr> - </tbody> -</table> - -<p>Back at the command prompt, type:</p> - -<pre>jpm run</pre> - -<p>This is the jpm command to run a new instance of Firefox with your add-on installed.</p> - -<p>If Firefox can not be located, you may need to provide the path to it (example in Ubuntu):</p> - - -<pre>jpm run -b /usr/bin/firefox</pre> - -<p>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 <a href="http://www.mozilla.org/" rel="noreferrer">http://www.mozilla.org/</a> loaded into it.</p> - -<p>That's all this add-on does. It uses two SDK modules: the <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action">action button</a> module, which enables you to add buttons to the browser, and the <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs" rel="noreferrer">tabs</a> 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.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/7643/mozilla-button.png" style="display: block; height: 221px; margin-left: auto; margin-right: auto; width: 382px;">Try editing this file. For example, we could change the page that gets loaded:</p> - -<pre class="brush: 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://developer.mozilla.org/"); -}</pre> - -<p>At the command prompt, execute <code>jpm run</code> again. This time clicking it takes you to <a href="https://developer.mozilla.org/">https://developer.mozilla.org/</a>.</p> - -<h2 id="Packaging_the_add-on">Packaging the add-on</h2> - -<p>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 <a href="https://addons.mozilla.org" rel="noreferrer">https://addons.mozilla.org</a> so other users can download and install them.</p> - -<p>To build an XPI, just execute the command <code>jpm xpi</code> from the add-on's directory:</p> - -<pre>jpm xpi -</pre> - -<p>You should see a message like:</p> - -<pre>JPM info Successfully created xpi at /path/to/getting-started/@getting-started.xpi -</pre> - -<p>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.</p> - -<h2 id="Summary">Summary</h2> - -<p>In this tutorial we've built and packaged an add-on using three commands:</p> - -<ul> - <li><code>jpm init</code> to initialize an empty add-on template</li> - <li><code>jpm run</code> to run a new instance of Firefox with the add-on installed, so we can try it out</li> - <li><code>jpm xpi</code> to package the add-on into an XPI file for distribution</li> -</ul> - -<p>These are the three main commands you'll use when developing SDK add-ons. There's comprehensive <a href="/en-US/Add-ons/SDK/Tools/jpm" rel="noreferrer">reference documentation</a> covering all the commands you can use and all the options they take.</p> - -<p>The add-on code itself uses two SDK modules, <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action">action button</a> and <a href="/en-US/Add-ons/SDK/High-Level_APIs/tabs" rel="noreferrer">tabs</a>. There's reference documentation for all the <a href="/en-US/Add-ons/SDK/High-Level_APIs" rel="noreferrer">high-level</a> and <a href="/en-US/Add-ons/SDK/Low-Level_APIs" rel="noreferrer">low-level</a> APIs in the SDK.</p> - -<h2 id="What's_next">What's next?</h2> - -<p>To get a feel for some of the things you can do with the SDK APIs, try working through some of the <a href="/en-US/Add-ons/SDK/Tutorials" rel="noreferrer">tutorials</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/index.html deleted file mode 100644 index 277c5573d9..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Tutorials -slug: Mozilla/Add-ons/SDK/Tutorials -tags: - - NeedsTranslation - - TopicStub -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials ---- -<p>Эта страница содержит практические статьи о том как выполнять конкретные задачи используя SDK.</p> - -<hr> -<h3 id="Начало_работы"><a name="getting-started">Начало работы</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Installation">Установка </a></dt> - <dd>Скачивание, установка и инициализация <span class="_Tgc">комплекта средств разработки</span> (SDK) для Windows, OS X и Linux.</dd> -</dl> - -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Troubleshooting">Исправление проблем </a></dt> - <dd>Несколько указаний для фиксации общих пролбем и получение дополнительной помощи.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Getting_started_with_cfx">Создание простого дополнения (Add-on) </a></dt> - <dd>Пошаговое руководство по созданию простого дополнения при помощи SDK и jpm.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Создание_пользовательского_интерфейса"><a name="create-user-interfaces">Создание пользовательского интерфейса</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Adding_a_Button_to_the_Toolbar">Добавление кнопи панели инструментов </a></dt> - <dd>Прикрепление кнопки к панели инструментов дополнений Firefox.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Add_a_Menu_Item_to_Firefox">Добавление элементов меню Firefox </a></dt> - <dd>Добавление элементов в основные меню Firefox.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Display_a_Popup">Отображение высплывающего окна (popup) </a></dt> - <dd>Отображение всплывающего диалогового окна и его реализация с помощью HTML и JavaScript.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Add_a_Context_Menu_Item">Добавление элемента контекстного меню</a></dt> - <dd>Добавление элементов контекстных меню Firefox.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Взаимодействие_с_браузером"><a name="interact-with-the-browser">Взаимодействие с браузером</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Open_a_Web_Page">Загрузка вебстраниц</a></dt> - <dd>Загрузка вебстраниц в новой вкладке или новом окне с использованием модуля вкладок (tabs module), и доступ к их содержимому.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Listen_for_Page_Load">Отслеживание загрузки страниц </a></dt> - <dd>Использование модуля вкладок (tabs module) для получения оповещений о загрузке новых вебстраниц и доступа к их содержимому.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/List_Open_Tabs">Получение списка открытых вкладок</a></dt> - <dd>Использование модуля вкладок (tabs module) для перебора открытых вкладок и доступа к их содержимому.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Изменение_вебстраниц"><a name="modify-web-pages">Изменение вебстраниц</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Modifying_Web_Pages_Based_on_URL">Изменение вебстраниц на основе URL </a></dt> - <dd>Создание фильтров для вебстраниц на основе их URL: всякий раз, когда загрузится вебстраница, чей URL соответствует фильтру, на ней выполнится заданный сценарий.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Modifying_the_Page_Hosted_by_a_Tab">Изменение активной вебстраницы </a></dt> - <dd>Динамическая загрузка сценария на текущую активную вебстраницу.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Техники_разработки"><a name="development-techniques">Техники разработки</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Logging">Логгирование </a></dt> - <dd>Вывод сообщений в консоль для диагностики.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Creating_reusable_modules">Создание повторно используемых модулей </a></dt> - <dd>Структурирование дополнения в отдельные модули, чтобы упростить разработку, отладку и поддержку. Создание повторно используемых пакетов, содержащих ваши модули, чтобы другие разработчики могли их использовать.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Unit_testing">Модульное тестирование </a></dt> - <dd>Написание и запуск модульных тестов с использованием тестовой среды SDK.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Chrome_authority">Полномочия Chrome </a></dt> - <dd>Получение доступа к объекту Components, позволит вашему дополнению загружать и использовать любой объект XPCOM.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Creating_event_targets">Создание целей события </a></dt> - <dd>Включение объектов вашего определения для выпуска собственных событий.</dd> -</dl> -</div> - -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Listening_for_load_and_unload">Отслеживание загрузки и выгрузки </a></dt> - <dd>Получение уведомлений, когда Firefox загрузил или выгрузил ваше дополнение и передача аргументов вашему дополнению из командной строки.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Add_a_Menu_Item_to_Firefox">Использование сторонних модулей </a></dt> - <dd>Установка и использование дополнительных модулей не входящих в SDK.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/l10n">Локализация </a></dt> - <dd>Написание локализуемого кода.</dd> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Mobile_development">Мобильная разработка </a></dt> - <dd><span class="short_text" id="result_box" lang="ru"><span class="alt-edited">Разработка дополнений для Firefox Mobile на Android.</span></span></dd> - <dt><a href="/en-US/Add-ons/Add-on_Debugger">Отладчик дополнения</a></dt> - <dd>Отладка JavaScript вашего дополнения.</dd> -</dl> -</div> -</div> - -<hr> -<h3 id="Объединение"><a name="putting-it-together">Объединение</a></h3> - -<div class="column-container"> -<div class="column-half"> -<dl> - <dt><a href="/en-US/Add-ons/SDK/Tutorials/Annotator">Аннотация дополнения </a></dt> - <dd><span id="result_box" lang="ru"><span>Пошаговое руководство относительно сложного дополнения.</span></span></dd> -</dl> -</div> -</div> - -<p> </p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html deleted file mode 100644 index 48b8923923..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/installation/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Installation -slug: Mozilla/Add-ons/SDK/Tutorials/Installation -translation_of: Mozilla/Add-ons/SDK/Tools/jpm#Installation ---- -<h2 id="Prerequisites">Prerequisites</h2> -<p>To develop with the Add-on SDK, you'll need:</p> -<ul> - <li><a href="http://www.python.org/">Python</a> 2.5, 2.6 or 2.7. Note that versions 3.x of Python are not supported on any platform. Make sure that Python is in your path.</li> - <li>Firefox.</li> - <li>The SDK itself: you can obtain the latest stable version of the SDK as a <a href="https://ftp.mozilla.org/pub/mozilla.org/labs/jetpack/jetpack-sdk-latest.tar.gz">tarball</a> or a <a href="https://ftp.mozilla.org/pub/mozilla.org/labs/jetpack/jetpack-sdk-latest.zip">zip file</a>.</li> -</ul> -<p>Alternatively, if you use Firefox Nightly, you can get the latest development version from its <a href="https://github.com/mozilla/addon-sdk">GitHub repository</a>.</p> -<h2 id="Installation_on_Mac_OS_X_Linux">Installation on Mac OS X / Linux</h2> -<p>Extract the file contents wherever you choose, and navigate to the root directory of the SDK with a shell/command prompt. For example:</p> -<pre>tar -xf addon-sdk.tar.gz -cd addon-sdk -</pre> -<p>Then run if you're a Bash user (most people are):</p> -<pre>source bin/activate -</pre> -<p>And if you're a non-Bash user, you should run:</p> -<pre>bash bin/activate -</pre> -<p>Your command prompt should now have a new prefix containing the name of the SDK's root directory:</p> -<pre>(addon-sdk)~/mozilla/addon-sdk > -</pre> -<h2 id="Installation_on_Mac_using_Homebrew">Installation on Mac using Homebrew</h2> -<p>If you're a Mac user, you can instead choose to use <a href="http://brew.sh/">Homebrew</a> to install the SDK, using the following command:</p> -<pre>brew install mozilla-addon-sdk</pre> -<p>Once this has completed successfully, you can use the <code>cfx</code> program at your command line at any time: you don't need to run bin/activate.</p> -<h2 id="Installation_on_Windows">Installation on Windows</h2> -<p>Extract the file contents wherever you choose, and navigate to the root directory of the SDK with a shell/command prompt. For example:</p> -<pre>7z.exe x addon-sdk.zip -cd addon-sdk -</pre> -<p>Then run:</p> -<pre>bin\activate -</pre> -<p>Your command prompt should now have a new prefix containing the full path to the SDK's root directory:</p> -<pre>(C:\Users\mozilla\sdk\addon-sdk) C:\Users\Work\sdk\addon-sdk> -</pre> -<h2 id="activate">activate</h2> -<p>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 <code>activate</code> again.</p> -<p>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.</p> -<h3 id="Making_activate_permanent">Making <code>activate</code> permanent</h3> -<p>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 <code>activate</code> every time you open up a new command prompt.</p> -<p>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.</p> -<h4 id="Windows">Windows</h4> -<p>On Windows, <code>bin\activate</code> uses <code>activate.bat</code>, and you can make activation permanent using the command line <code>setx</code> tool or the Control Panel.</p> -<h4 id="LinuxMac_OS_X">Linux/Mac OS X</h4> -<p>On Linux and Mac OS X, <code>source bin/activate</code> uses the <code>activate</code> bash script, and you can make activation permanent using your <code>~/.bashrc</code> (on Linux) or <code>~/.bashprofile</code> (on Mac OS X).</p> -<p>As an alternative to this, you can create a symbolic link to the <code>cfx</code> program in your <code>~/bin</code> directory:</p> -<pre>ln -s PATH_TO_SDK/bin/cfx ~/bin/cfx -</pre> -<p>If you used Homebrew to install the SDK, the environment variables are already set permanently for you.</p> -<h2 id="Sanity_check">Sanity check</h2> -<p>Run this at your shell prompt:</p> -<pre>cfx -</pre> -<p>It should produce output whose first line looks something like this, followed by many lines of usage information:</p> -<pre>Usage: cfx [options] [command] -</pre> -<p>This is the <a href="/en-US/Add-ons/SDK/Tools/cfx"><code>cfx</code> command-line program</a>. 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.</p> -<h2 id="Problems">Problems?</h2> -<p>Try the <a href="/en-US/Add-ons/SDK/Tutorials/Troubleshooting">Troubleshooting</a> page.</p> -<h2 id="Next_Steps">Next Steps</h2> -<p>Next, take a look at the <a href="/en-US/Add-ons/SDK/Tutorials/Getting_Started_With_cfx">Getting Started With cfx</a> tutorial, which explains how to create add-ons using the <code>cfx</code> tool.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/creating_annotations/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/creating_annotations/index.html deleted file mode 100644 index 07cecddaf5..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/creating_annotations/index.html +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Добавление заметок -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Creating_annotations -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Creating_annotations ---- -<p>Мы будем использовать два объекта для создания заметок: модификатор страницы - чтобы найти элементы, для которых пользователь может оставить заметку и панель для ввода текста заметки.</p> -<h2 id="Селектор_модификации_страницы">Селектор модификации страницы</h2> -<h3 id="Селектор_контент-скриптов">Селектор контент-скриптов</h3> -<p>Контент-скрипт для селекторамодификации страницы будет ипользовать <a href="http://jquery.com/">jQuery</a> для поиска элементов и манипуляций над ними.</p> -<p>Эго главная задача - обработка "подходящего элемента": это элемент страницы, который подходит для добавления заметки на него. Подходящий элемент будет подсвечен и будет иметь обработчик событий, который будет отправлять сообщения основному коду расширения.</p> -<p>Селектор модификации страницы может быть активирован или деактивирован используя сообщение от основного кода расширения. По-умолчанию он деактивирован:</p> -<pre class="brush: js">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(); - } -});</pre> -<p>Данный селектор ожидает вхождения события <a href="http://api.jquery.com/mouseenter/">jQuery mouseenter</a>.</p> -<p> 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 <code>"id"</code>. The idea here is to make it more likely that the annotator will be able to identify annotated elements correctly later on.</p> -<p>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 <code>show</code> back to the main add-on code. The <code>show</code> message contains: the URL for the page, the ID attribute value, and the text content of the page element.</p> -<pre class="brush: js">$('*').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() - ] - ); - }); -});</pre> -<p>Conversely, the add-on resets the matched element on <a href="http://api.jquery.com/mouseout/">mouseout</a>:</p> -<pre class="brush: js">$('*').mouseout(function() { - resetMatchedElement(); -});</pre> -<p>Save this code in a new file called <code>selector.js</code> in your add-on's <code>data</code> directory.</p> -<p>Because this code uses jQuery, you'll need to <a href="http://docs.jquery.com/Downloading_jQuery">download</a> that as well, and save it in <code>data</code>.</p> -<h3 id="Updating_main.js">Updating main.js</h3> -<p>Go back to <code>main.js</code> and add the code to create the selector into the <code>main</code> function:</p> -<pre class="brush: js">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); - }); - } -});</pre> -<p>Make sure the name you use to load jQuery matches the name of the jQuery version you downloaded.</p> -<p>The page-mod matches all pages, so each time the user loads a page the page-mod emits the <code>attach</code> event, which will call the listener function we've assigned to <code>onAttach</code>. The handler is passed a <a href="/en-US/Add-ons/SDK/Low-Level_APIs/content_worker">worker</a> 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 <code>page-mod</code> uses workers, see the <a href="/en-US/Add-ons/SDK/High-Level_APIs/page-mod">page-mod documentation</a>.</p> -<p>In the attach handler we do three things:</p> -<ul> - <li>send the content script a message with the current activation status</li> - <li>add the worker to an array called <code>selectors</code> so we can send it messages later on</li> - <li>assign a message handler for messages from this worker. If the message is <code>show</code> we will just log the content for the time being. If the message is <code>detach</code> we remove the worker from the <code>selectors</code> array.</li> -</ul> -<p>At the top of the file import the <code>page-mod</code> module and declare an array for the workers:</p> -<pre class="brush: js">var pageMod = require('sdk/page-mod'); -var selectors = [];</pre> -<p>Add <code>detachWorker</code>:</p> -<pre class="brush: js">function detachWorker(worker, workerArray) { - var index = workerArray.indexOf(worker); - if(index != -1) { - workerArray.splice(index, 1); - } -}</pre> -<p>Edit <code>toggleActivation</code> to notify the workers of a change in activation state:</p> -<pre class="brush: js">function activateSelectors() { - selectors.forEach( - function (selector) { - selector.postMessage(annotatorIsOn); - }); -} - -function toggleActivation() { - annotatorIsOn = !annotatorIsOn; - activateSelectors(); - return annotatorIsOn; -}</pre> -<p><span class="aside">We'll be using this URL in all our screenshots. Because <code>cfx run</code> doesn't preserve browsing history, if you want to play along it's worth taking a note of the URL.</span></p> -<p>Save the file and execute <code>cfx run</code> again. Activate the annotator by clicking the widget and load a page: the screenshot below uses <a href="http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/">http://blog.mozilla.com/addons/2011/02/04/ overview-amo-review-process/</a>. You should see the highlight appearing when you move the mouse over certain elements:</p> -<p><img alt="" src="https://mdn.mozillademos.org/files/6681/highlight.png" style="display: block; margin-left: auto; margin-right: auto;">Click on the highlight and you should see something like this in the console output:</p> -<pre> 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. -</pre> -<h2 id="Annotation_Editor_Panel">Annotation Editor Panel</h2> -<p>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.</p> -<p>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.</p> -<p>So create a subdirectory under <code>data</code> called <code>editor</code>. This will contain two files: the HTML content, and the content script.</p> -<h3 id="Annotation_Editor_HTML">Annotation Editor HTML</h3> -<p>The HTML is very simple:</p> -<pre class="brush: html"><!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></pre> -<p>Save this inside <code>data/editor</code> as <code>annotation-editor.html</code>.</p> -<h3 id="Annotation_Editor_Content_Script">Annotation Editor Content Script</h3> -<p>In the corresponding content script we do two things:</p> -<ul> - <li>handle a message from the add-on code by giving the text area focus</li> - <li>listen for the return key and when it is pressed, send the contents of the text area to the add-on.</li> -</ul> -<p>Here's the code:</p> -<pre class="brush: js">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(); -});</pre> -<p>Save this inside <code>data/editor</code> as <code>annotation-editor.js</code>.</p> -<h3 id="Updating_main.js_Again">Updating main.js Again</h3> -<p>Now we'll update <code>main.js</code> again to create the editor and use it.</p> -<p>First, import the <code>panel</code> module:</p> -<pre class="brush: js">var panels = require('sdk/panel');</pre> -<p>Then add the following code to the <code>main</code> function:</p> -<pre class="brush: js">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'); - } -});</pre> -<p>We create the editor panel but don't show it. We will send the editor panel the <code>focus</code> 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.</p> -<p>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 <code>show</code> message we assign the content of the message to the panel using a new property "annotationAnchor", and show the panel:</p> -<pre class="brush: js">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); - }); - } -});</pre> -<p>Execute <code>cfx run</code> 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:</p> -<p><img alt="" src="https://mdn.mozillademos.org/files/6683/editor-panel.png" style="display: block; margin-left: auto; margin-right: auto;">Enter the note and press the return key: you should see console output like this:</p> -<pre> 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. -</pre> -<p>That's a complete annotation, and in the next section we'll deal with <a href="/en-US/Add-ons/SDK/Tutorials/Annotator/Storing_annotations">storing it</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/implementing_the_widget/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/implementing_the_widget/index.html deleted file mode 100644 index ef43991658..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/implementing_the_widget/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Реализация Виджета -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Implementing_the_widget -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Implementing_the_widget ---- -<p>Мы хотим, чтобы виджет выполнял две вещи:</p> -<ul> - <li>При клике левой кнопкой мыши, Виджет должен активировать или деактивировать Аннотатор;</li> - <li>При клике правой кнопкой, Виджет должен отобразить список всех заметок, созданных пользователем.</li> -</ul> -<p>Так как событие <code>click</code> не различает левую и правую кнопки мыши, мы будем использовать контент-скрипт для захвата событий клика мышью и отправлять соответствующее сообщение назад, нашему расширению.</p> -<p>Виджет должен иметь две иконки: одна для активного состояния, вторая для неактивного.</p> -<p>В итоге нам понадобится создать три файла: контент-скрипт для Виджета и две иконки.</p> -<p>Внутри папки <code>data</code> создайте папку с именем <code>widget</code>. В этой папке мы будем хранить файлы Виджета. (Вам не обязательно создавать отдельную папку, можете просто хранить файлы Виджета в папке <code>data</code>. Но в нашем случае, расширение будет хорошо структурировано.)</p> -<h2 id="Контент-скрипт_Виджета">Контент-скрипт Виджета</h2> -<p>Контент-скрипт Виджета просто следит за нажатиями левой и правой кнопок мыши и отправляет соответствующее сообщение коду расширения:</p> -<pre class="brush: js">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);</pre> -<p>Сохраните этот файл в папку <code>data/widget</code> под названием <code>widget.js</code>.</p> -<h2 id="Иконки_Виджета">Иконки Виджета</h2> -<p>Вы можете скопировать эти иконки:</p> -<p><img alt="" src="https://mdn.mozillademos.org/files/6673/pencil-off.png"><img alt="" src="https://mdn.mozillademos.org/files/6675/pencil-on.png" style="width: 32px; height: 32px;"></p> -<p>(Вы также можете создать свои собственные иконки, если чуствуете, что вас поситила муза.) Сохраните их в папку <code>data/widget</code>.</p> -<h2 id="main.js">main.js</h2> -<p>Теперь, в папке <code>lib</code> откройте <code>main.js</code> и добавьте следующий код:</p> -<pre class="brush: 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'); - }); -}</pre> -<p>Аннотатор по-умолчанию отключен. Этот скрипт создает Виджет и реагирует на сообщения контент-скрипта, путем переключения состояния Виджета. Внимание: согласно багу<span class="aside"> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=626326">bug 626326</a>, контекстное меню панели дополнений будет отображаться вне зависимости от вызова <code>event.preventDefault()</code> в контент-скрипте Виджета.</span> Так как мы пока не имеем кода для отображения заметок, мы просто выведем в консоль событие нажатия правой кнопки.</p> -<p>Теперь, перейдя в папку <code>annotator</code> выполните команду <code>cfx run</code>. Вы должны увидеть Виджет в панели дополнений:</p> -<p><img alt="" src="https://mdn.mozillademos.org/files/6679/widget-icon.png" style="width: 405px; height: 166px; display: block; margin-left: auto; margin-right: auto;"></p> -<p>Левый и правый клики должы выводить соответсвующие сообщения в консоль, и левый клик также должен менять иконку для отображения состояния активности Виджета.</p> -<p> </p> -<p>Далее мы добавим реализацию функции <a href="/en-US/Add-ons/SDK/Tutorials/Annotator/Creating_annotations">создания аннотаций</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/index.html deleted file mode 100644 index eab37823c0..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Комментатор -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator ---- -<p>{{AddonSidebar}}</p> - -<div class="warning"> -<p>Запрещено в Firefox 29 и удалено в Firefox 38.</p> - -<p>Предупреждение: это руководство пологается на впоследствии удалённый Widget API и больше не работает с Firefox.</p> - -<p>The widget API is deprecated from Firefox 29 onwards. Please see the <a href="/en-US/Add-ons/SDK/High-Level_APIs/ui">ui module</a> for replacements. In particular, for a simple button, try the <a href="/en-US/Add-ons/SDK/High-Level_APIs/ui#ActionButton">action button</a> or <a href="/en-US/Add-ons/SDK/High-Level_APIs/ui#ToggleButton">toggle button</a> APIs, and for a more complex widget try the <a href="/en-US/Add-ons/SDK/High-Level_APIs/ui#Toolbar">toolbar</a> or <a href="/en-US/Add-ons/SDK/High-Level_APIs/ui#Sidebar">sidebar</a> APIs.</p> -</div> - -<p>В этом уроке мы создадим расширение, которое использует множество различных компонентов <a href="/en-US/Add-ons/SDK/High-Level_APIs">высокоуровнего API</a>.</p> - -<p>Это расширение (Аннотатор) позволит пользователю выделять элементы веб-страниц и добавлять к ним заметки (аннотации). Аннотатор будет сохранять заметки, добавленные пользователем. Когда пользователь посещает веб-страницу, содержащую элементы с прикрепленными к ним заметками - эти элементы подсвечиваются. Если пользователь наведет курсор на такой элемент страницы, то будет отображена заметка, ассоциированная с этим элементом.</p> - -<p>Далее мы кратко рассмотрим архитектуру Аннотатора и поэтапно пройдемся по реализации разных частей расширения.</p> - -<p>Завершенное расширение вы можете найти в <a href="https://github.com/mozilla/addon-sdk/tree/master/examples/annotator">папке <code>examples</code> из SDK</a>.</p> - -<ul> - <li><a href="/ru/docs/Mozilla/Add-ons/SDK/Tutorials/%D0%90%D0%BD%D0%BD%D0%BE%D1%82%D0%B0%D1%82%D0%BE%D1%80/Overview">Краткий обзор архитектуры</a><br> - </li> - <li><a href="/ru/docs/Mozilla/Add-ons/SDK/Tutorials/%D0%90%D0%BD%D0%BD%D0%BE%D1%82%D0%B0%D1%82%D0%BE%D1%80/Implementing_the_widget">Реализация Виджета</a><br> - </li> - <li><a href="/ru/docs/Mozilla/Add-ons/SDK/Tutorials/%D0%90%D0%BD%D0%BD%D0%BE%D1%82%D0%B0%D1%82%D0%BE%D1%80/Creating_annotations">Добавление заметок</a><br> - </li> - <li><a href="/en-US/Add-ons/SDK/Tutorials/Annotator/Storing_annotations">Хранение заметок</a><br> - </li> - <li><a href="/en-US/Add-ons/SDK/Tutorials/Annotator/Displaying_annotations">Отображение заметок</a></li> -</ul> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/overview/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/overview/index.html deleted file mode 100644 index 08e4713b33..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/аннотатор/overview/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Краткий обзор -slug: Mozilla/Add-ons/SDK/Tutorials/Аннотатор/Overview -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Annotator/Overview ---- -<p>Аннотатор использует контент-скрипты для реализации пользовательских интерфейсов, получения ввода, и для работы со страницами, посещаемыми пользователем.</p> -<p>Модуль <code>main</code> содержит логику приложения и производит операции между различными объектами SDK.</p> -<p>Операции между модулем <code>main</code> и различными контент-скриптами можно изобразить следующим образом:</p> -<p><img alt="" src="https://mdn.mozillademos.org/files/6671/annotator-design.png" style="display: block; margin-left: auto; margin-right: auto;"></p> -<h2 id="Пользовательский_интерфейс">Пользовательский интерфейс</h2> -<p>Основной пользовательский интерфейс состоит из Виджета и трех панелей:</p> -<ul> - <li>Виджет (<code><a href="/en-US/Add-ons/SDK/High-Level_APIs/widget">widget</a></code>) используется для активации Аннотатора и для отображения списка всех сохраненных заметок;</li> - <li>Панель (<code><a href="/en-US/Add-ons/SDK/High-Level_APIs/panel">panel</a></code>) <strong>annotation-editor</strong> позволит пользователю добавить новую заметку;</li> - <li>Панель <strong>annotation-list</strong> будет отображать список всех сохраненных заметок;</li> - <li>Панель <strong>annotation</strong> будет отображать одну заметку.</li> -</ul> -<p>В дополнении, мы будем использовать модуль Оповещений (<a href="/en-US/Add-ons/SDK/High-Level_APIs/notifications"><code>notifications</code></a>), чтобы сообщать пользователю, когда в хранилище закончилось свободное место.</p> -<h2 id="Работаем_с_DOM">Работаем с DOM</h2> -<p>Мы будем использовать два объекта <a href="/en-US/Add-ons/SDK/High-Level_APIs/page-mod"><code>page-mods</code></a> для произведения операций над DOM веб-страниц, которые посещает пользователь:</p> -<ul> - <li> - <p>Объект <strong>selector</strong> позволит пользователю выбрать элемент для добавления заметки к нему. Он идентифицирует элементы страницы, которые подходят для заметок, подсвечивает их при наведении курсора мыши и сообщает основному коду расширения когда пользователь кликает по подсвеченному элементу;</p> - </li> - <li> - <p>Объект <strong>matcher</strong> отвечает за поиск элементов с заметками: он инициализируется со списком заметок и осуществляет поиск веб-сраниц с элементами, ассоциированными с этими заметками. Он также подсвечивает все элементы, ассоциированные с заметками. Когда пользователь наводит курсор мыши на элемент с заметкой, matcher сообщает основному коду расширения, который, в свою очередь, отображает панель с одной заметкой.</p> - </li> -</ul> -<h2 id="Обработка_данных">Обработка данных</h2> -<p>Мы будем использовать модуль <a href="/en-US/Add-ons/SDK/High-Level_APIs/simple-storage"><code>simple-storage</code></a> для хранения заметок.</p> -<p>Поскольку мы сохраняем потенциально секретную информацию, мы хотим оградить пользователя от создания заметок в приватном режиме браузера. Простейший способ решения этой проблемы, это удаление ключа <a href="/en-US/Add-ons/SDK/Tools/package_json#permissions"><code>"private-browsing"</code></a> из файла "package.json" расширения. Если мы удалим этот ключ, то расширение не получит доступ к окнам в режиме приватного просмотра и Виджет Аннотатора не будет отображаться в приватных окнах.</p> -<h2 id="Приступаем_к_работе">Приступаем к работе</h2> -<p>Давайте начнем с создания папки, с именем "annotator". Перейдите в эту папку и введите <code>cfx init</code>.</p> -<p>Далее мы <a href="/en-US/Add-ons/SDK/Tutorials/Annotator/Implementing_the_widget">разработаем Виджет</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/добавление_кнопки_на_панель_инструментов/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/добавление_кнопки_на_панель_инструментов/index.html deleted file mode 100644 index 7b6e8bf507..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/добавление_кнопки_на_панель_инструментов/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Добавление кнопки на панель инструментов -slug: Mozilla/Add-ons/SDK/Tutorials/Добавление_кнопки_на_панель_инструментов -tags: - - Add-on SDK - - Дополнение -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Adding_a_Button_to_the_Toolbar ---- -<div class="blockIndicator warning"> -<p>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.</p> -</div> - -<p>{{LegacyAddonsNotice}}{{AddonSidebar}}</p> - -<div class="note"> -<p><span>Для понимания этого руководства необходимо изучить статью <a href="/en-US/docs/Mozilla/Add-ons/SDK/Tutorials/Getting_Started_%28jpm%29">basics of <code>jpm (основы jpm)</code></a>. </span></p> -</div> - -<p>Для добавления кнопки на панель инструментов (toolbar, тулбар) используются модули <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action">action button</a> или <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_toggle">toggle button</a>.</p> - -<p>Создайте новую папку, перейдите в неё и запустите <code>jpm init</code>, приняв всё по умолчанию.</p> - -<p>Создайте папку <strong>"data"</strong></p> - -<pre>mkdir data</pre> - -<p>и сохраните три файла иконок в этой папке:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7635/icon-16.png" style="height: 16px; width: 16px;"></td> - <td>icon-16.png</td> - </tr> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7637/icon-32.png" style="height: 32px; width: 32px;"></td> - <td>icon-32.png</td> - </tr> - <tr> - <td><img alt="" src="https://mdn.mozillademos.org/files/7639/icon-64.png" style="height: 64px; width: 64px;"></td> - <td>icon-64.png</td> - </tr> - </tbody> -</table> - -<p>После, откройте файл "index.js", расположенный в корне каталога дополнения, и допишите этот код:</p> - -<pre class="brush: 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/"); -}</pre> - -<p>Запустите дополнение через <code>jpm run</code>. Кнопка будет добавлена на тулбар (ищите сверху в окне браузера):</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/7641/mozilla-button.png" style="display: block; height: 221px; margin-left: auto; margin-right: auto; width: 382px;">Вы не сможете установить место первоначального появления кнопки, но пользователь сможет её переместить, используя настройки браузера. Атрибут <code>id</code> является обязательным. Он используется, в частности, для запоминания позиции кнопки на панели, поэтому в следующих версиях своего дополнения вы его не сможете изменить.</p> - -<p>Нажатие кнопки откроет в новой вкладке сайт <a href="https://www.mozilla.org/en-US/">https://www.mozilla.org/</a> .</p> - -<h2 id="Задание_иконки">Задание иконки</h2> - -<p>Свойство icon может содержать одну иконку или набор (различных размеров, как в примере выше). Если указать набор иконок разных размеров, то браузер будет автоматически выбирать размер в зависимости от разрешения экрана и расположения на экране. <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action#ActionButton(options)">Более подробная информация о иконках</a>.</p> - -<p>Файл с иконкой должен быть внутри дополнения. Недопустимы ссылки на внешние фалы.</p> - -<p>Вы можете изменить иконку в любое время через установку свойства <code>icon</code> кнопки. Также можно изменить иконку и другие свойства состояния глобально для окна брайзера или только для вкладки. <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action#Updating_state">Узнать об этом можно в статье</a>.</p> - -<h2 id="Привязка_панели">Привязка панели</h2> - -<p>Если необходимо привязать к кнопке панель, то используйте <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_toggle">toggle button</a> API. Этот API такой же как action button API, кроме того, что добавлено булево свтйство <code>checked, </code>которое переключается, когда нажимается конпка. Для связи в панелью нужнопередать кнопку в функцию <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/panel#show(options)"><code>show()</code></a> панели. Для уточнения деталей, изучите документацию <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_toggle#Attaching_panels_to_buttons">toggle button's documentation</a>.</p> - -<h2 id="Вывод_сложного_контента">Вывод сложного контента</h2> - -<p>Для созлания более сложного пользовательского интерфейса, чем доступен через кнопку, используйте <a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_toolbar">toolbar</a> API. С этим API вы получите доступ к полным гризонтальным полосам тулбара. Можно добавлять кнопки на панель, и фреймы (<a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_frame">frames</a>), которые могут содержать HTML, CSS и JavaScript.</p> - -<h2 id="Материал_для_изучения">Материал для изучения</h2> - -<ul> - <li><a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action">action button reference</a></li> - <li><a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_toggle">toggle button reference</a></li> - <li><a href="/en-US/Add-ons/SDK/Low-Level_APIs/ui_toolbar">toolbar reference</a></li> -</ul> diff --git a/files/ru/mozilla/add-ons/sdk/tutorials/протоколирование/index.html b/files/ru/mozilla/add-ons/sdk/tutorials/протоколирование/index.html deleted file mode 100644 index d0ab8d6f79..0000000000 --- a/files/ru/mozilla/add-ons/sdk/tutorials/протоколирование/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Протоколирование (Логирование) -slug: Mozilla/Add-ons/SDK/Tutorials/Протоколирование -tags: - - Логирование - - Протоколирование -translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Logging ---- -<div class="blockIndicator warning"> -<p>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.</p> -</div> - -<p>{{LegacyAddonsNotice}}{{AddonSidebar}}</p> - -<div class="note"><span>Перед использованием, вам нужно изучить <a href="/en-US/docs/Mozilla/Add-ons/SDK/Tutorials/Getting_Started_%28jpm%29">основы <code>jpm</code></a>. </span></div> - -<p><a href="https://developer.mozilla.org/en/DOM/console">Консоль для DOM-объекта</a> полезна для отладки JavaScript. Так как DOM-объекты недоступны для главного кода дополнения (add-on), то SDK предоставляет свой собственный глобальный <code>объект</code> <code>"консоль" (console)</code> с большинством таких же методов, как и у DOM-<code>консоли</code>, включая методы для протоколирвоания ошибок (error), предупреждений (warning) или информационных сообщений. Для доступа к консоли не нужно получать что-либо, используя <code>require()</code>. Она уже доступна автоматически.</p> - -<p>Метод <code>console.log()</code> выводит информационное сообщение:</p> - -<pre class="brush: js">console.log("Hello World"); -</pre> - -<p>Попробуйте:</p> - -<ul> - <li>создайте новую папку и перейдите в неё</li> - <li>выполните jpm init со значениями по умолчанию</li> - <li>откройте "index.js" и добавьте строку, указанную в примере выше</li> - <li>выполните <code>jpm run</code></li> -</ul> - -<p>Firefox запустится, и в терминале, где вы ввели <code>jpm run</code>, появится следующая строка:</p> - -<pre>info: Hello World! -</pre> - -<h2 id="Консоль_в_скриптах_Content_Scripts"><code>Консоль</code> в скриптах <code>Content Scripts</code></h2> - -<p>Вы можете использовать консоль в скриптах <code><a href="/en-US/Add-ons/SDK/Guides/Content_Scripts">content scripts</a></code> так же, как и вашем главном коде дополнения. Следующий аддон (add-on) выведет в лог HTML-содержимое каждой закладки, загруженной пользователем, используя <code>console.log()</code> изнутри скрипта <code>content script</code>:</p> - -<pre class="brush: js">require("sdk/tabs").on("ready", function(tab) { - tab.attach({ - contentScript: "console.log(document.body.innerHTML);" - }); -}); -</pre> - -<h2 id="Консоль_Output">Консоль Output</h2> - -<p>Если вы запускаете дополнение из терминала (например, выполня <code>jpm run</code> или <code>jpm test</code>), тогда сообщения консоли появятся в этом же терминале.</p> - -<p>Если вы установили расширение в Firefox тогде сообщения появятся в <a href="/en-US/docs/Tools/Browser_Console">консоли браузера</a> Firefox.</p> - -<p>Но обратите внимание, что <strong>по умолчанию вызовы <code>console.log()</code> не отобразят ничего в Error Console для любых установленных дополнений</strong>. Это правило работает и для дополнений, установленных с использованием Add-on Builder, и для установленных с помощью утилит, таких как <a href="https://addons.mozilla.org/en-US/firefox/addon/autoinstaller/">Extension Auto-installer</a>.</p> - -<p>Смотрите <a href="/en-US/Add-ons/SDK/Tools/console#Logging_Levels">"Уровни логирования"</a> в справочной документации для более подробной информации.</p> - -<h2 id="Дальнейшее_изучение">Дальнейшее изучение</h2> - -<p>Полное <code>API консоли</code> смотри в <a href="/en-US/Add-ons/SDK/Tools/console">API-справочнике</a>.</p> diff --git a/files/ru/mozilla/add-ons/sdk/проба/index.html b/files/ru/mozilla/add-ons/sdk/проба/index.html deleted file mode 100644 index 987a420410..0000000000 --- a/files/ru/mozilla/add-ons/sdk/проба/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Builder -slug: Mozilla/Add-ons/SDK/проба -translation_of: Archive/Add-ons/Add-on_SDK/Builder ---- -<p>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 <code>cfx</code> command line tool. It was retired on April 1, 2014, and the "builder.addons.mozilla.org" domain now redirects to this page.<br> - <br> - 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 <a href="/en-US/Add-ons/SDK/High-Level_APIs">high-level</a> and <a href="/en-US/Add-ons/SDK/Low-Level_APIs">low-level</a> APIs used for Builder add-ons are exactly the same for Builder and SDK. To switch to the SDK:</p> - -<ul> - <li><a href="/en-US/Add-ons/SDK/Tutorials/Installation">install the SDK locally</a></li> - <li>get to know the cfx command line tool, with this <a href="/en-US/Add-ons/SDK/Tutorials/Getting_started">introductory walkthrough</a> and the <a href="/en-US/Add-ons/SDK/Tools/cfx">detailed <code>cfx</code> reference</a></li> - <li>get to know the <a href="/en-US/Add-ons/SDK/Tools/package_json">package.json</a> file used to configure attributes of your add-on</li> -</ul> diff --git a/files/ru/mozilla/add-ons/загрузочные_расширения/index.html b/files/ru/mozilla/add-ons/загрузочные_расширения/index.html deleted file mode 100644 index 934e40e904..0000000000 --- a/files/ru/mozilla/add-ons/загрузочные_расширения/index.html +++ /dev/null @@ -1,353 +0,0 @@ ---- -title: Загружаемые расширения -slug: Mozilla/Add-ons/загрузочные_расширения -tags: - - Bootstrapped - - Extensions - - add-on - - Дополнения -translation_of: Archive/Add-ons/Bootstrapped_extensions ---- -<div class="blockIndicator warning"> -<p>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.</p> -</div> - -<p>{{LegacyAddonsNotice}}{{AddonSidebar}}</p> - -<p>{{ gecko_minversion_header("2.0") }}</p> - -<p>К традиционным расширениям относятся оверлеи (<strong>overlays</strong>), в их случае приложение может загрузить XUL из пакета расширения и автоматически применить их на верхнем слое своего UI (интерфейса пользователя). При этом создаются расширения, которые добавляются в пользовательский интерфейс относительно легко, но в этом случае обновление, установка или отмена действия расширения требуют перезагрузку приложения.</p> - -<p>Движок Gecko 2.0 {{ geckoRelease("2.0") }} вводит <strong>загружаемые расширения</strong> (<strong>bootstrapped extensions</strong>). Это специальные расширения, которые вместо использования наложения на интерфейс, сами програмно добавляют себя в приложение. Это делается запуском специального скрипта из файла, который включен в расширение и содержит функции, вызываемые браузером, для того чтобы установить, удалить, загрузить, выгрузить.</p> - -<p>Приложение делает вызовы из из этого файла со скриптом; расширение ответственно за добавление и удаление своего интерфейса пользователя и обработку любых других установок и завершения задач, которые требовались в процессе работы.</p> - -<p>Эта статья поясняет как работают загружаемые расширения. Изучите следующее <a href="/en-US/Add-ons/How_to_convert_an_overlay_extension_to_restartless">руководство по преобразованию приложений-оверлеев (overlay) в приложения, не требующие перезагрузки (restartless, то есть bootstrapped)</a>, для получения пошагового руководства по переходу.</p> - -<h2 id="The_startup_and_shutdown_process">The startup and shutdown process</h2> - -<p>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 <code>startup()</code> function is called, it must manually inject its user interface and other behavior into the application. Similarly, when its <code>shutdown()</code> function is called, it must remove anything that it has added to the application, as well as all references to any of its objects.</p> - -<p>There are several scenarios in which the <code>startup()</code> function may be called; for example:</p> - -<ul> - <li>When the extension is first installed, assuming that it's both compatible with the application and is enabled.</li> - <li>When the extension becomes enabled using the add-ons manager window.</li> - <li>When the application is started up, if the extension is enabled and compatible with the application.</li> -</ul> - -<p>Some examples of when the <code>shutdown()</code> function may be called:</p> - -<ul> - <li>When the extension is uninstalled, if it's currently enabled.</li> - <li>When the extension becomes disabled.</li> - <li>When the user quits the application, if the extension is enabled.</li> -</ul> - -<h2 id="Notes_on_modifying_the_application_user_interface">Notes on modifying the application user interface</h2> - -<h3 id="chrome.manifest_in_bootstrapped_add-ons">chrome.manifest in bootstrapped add-ons</h3> - -<p>You can use a <a href="/en-US/docs/Chrome_Registration"><code>chrome.manifest</code></a> file in bootstrapped add-ons to:</p> - -<ul> - <li>Make your add-on's content available via a <code>chrome://</code> URL (using the <code>content</code>, <code>locale</code>, and <code>skin</code> instructions in the manifest).</li> - <li>Replace existing <code>chrome://</code> URIs with your content (using the <code>override</code> instruction).</li> -</ul> - -<p>Not all <code>chrome.manifest</code> instructions are supported in bootstrapped add-ons, for example you still cannot register <a href="/en-US/docs/XUL_Overlays">XUL Overlays</a> from a bootstrapped add-on. See the <a href="/en-US/docs/Chrome_Registration"><code>chrome.manifest</code></a> documentation for details.</p> - -<p>In Firefox 10 and later the <code>chrome.manifest</code> file located in the root of the add-on's XPI (i.e. a sibling of the <code>install.rdf</code>) 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.</p> - -<h3 id="Adding_user_interface_manually">Adding user interface manually</h3> - -<p>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.</p> - -<p>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 <code>document.getElementById("main-menubar")</code>.</p> - -<p>Be sure that at shutdown time, you remove any user interface you've added.</p> - -<h2 id="Creating_a_bootstrapped_extension">Creating a bootstrapped extension</h2> - -<p>To mark an extension as bootstrappable, you need to add the following element to its <a href="/en-US/docs/Install_Manifests">install manifest</a>:</p> - -<pre><code><em:bootstrap>true</em:bootstrap></code></pre> - -<p>Then you need to add a <a href="/en-US/docs/Extensions/bootstrap.js"><code><strong>bootstrap.js</strong></code> file</a> that contains the required functions; this should be alongside the <a href="/en-US/docs/Install_Manifests"><code>install.rdf</code> file</a> in the extension's package.</p> - -<h3 id="Backward_compatibility">Backward compatibility</h3> - -<p>Because older versions of Firefox don't know about the <code>bootstrap</code> property or <code>bootstrap.js</code> 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 <code>bootstrap.js</code> script, ignoring the components and overlays, while older versions will use the overlays.</p> - -<h2 id="Bootstrap_entry_points">Bootstrap entry points</h2> - -<p>The <code>bootstrap.js</code> 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.</p> - -<h3 id="startup">startup</h3> - -<p>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.</p> - -<p>This is when your add-on should inject its UI, start up any tasks it may need running and so forth.</p> - -<pre>void startup( - data, - reason -); -</pre> - -<h6 id="Parameters">Parameters</h6> - -<dl> - <dt><code>data</code></dt> - <dd>A <a href="#Bootstrap_data">bootstrap data structure</a>.</dd> - <dt><code>reason</code></dt> - <dd>One of the <a href="#Reason_constants">reason constants</a>, indicating why the extension is being started up. This will be one of <code>APP_STARTUP</code>, <code>ADDON_ENABLE</code>, <code>ADDON_INSTALL</code>, <code>ADDON_UPGRADE</code>, or <code>ADDON_DOWNGRADE</code>.</dd> -</dl> - -<h3 id="shutdown">shutdown</h3> - -<p>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.</p> - -<pre>void shutdown( - data, - reason -); -</pre> - -<h6 id="Parameters_2">Parameters</h6> - -<dl> - <dt><code>data</code></dt> - <dd>A <a href="#Bootstrap_data">bootstrap data structure</a>.</dd> - <dt><code>reason</code></dt> - <dd>One of the <a href="#Reason_constants">reason constants</a>, indicating why the extension is being shut down. This will be one of <code>APP_SHUTDOWN</code>, <code>ADDON_DISABLE</code>, <code>ADDON_UNINSTALL</code>, <code>ADDON_UPGRADE</code>, or <code>ADDON_DOWNGRADE</code>.</dd> -</dl> - -<h3 id="install">install</h3> - -<p>Your bootstrap script must include an <code>install()</code> function, which the application calls before the first call to <code>startup()</code> after the extension is installed, upgraded, or downgraded.</p> - -<pre>void install( - data, - reason -); -</pre> - -<h6 id="Parameters_3">Parameters</h6> - -<dl> - <dt><code>data</code></dt> - <dd>A <a href="#Bootstrap_data">bootstrap data structure</a>.</dd> - <dt><code>reason</code></dt> - <dd>One of the <a href="#Reason_constants">reason constants</a>, indicating why the extension is being installed. This will be one of <code>ADDON_INSTALL</code>, <code>ADDON_UPGRADE</code>, or <code>ADDON_DOWNGRADE</code>.</dd> -</dl> - -<h3 id="uninstall">uninstall</h3> - -<p>This function is called after the last call to <code>shutdown()</code> before a particular version of an extension is uninstalled.</p> - -<div class="note"><strong>Note:</strong> 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.</div> - -<div class="note"><strong>Note:</strong> The uninstall function fires on downgrade and upgrade as well so you should make sure it is an uninstall by doing this:<br> -<code>function uninstall(aData, aReason) {</code><br> -<code>if (aReason == ADDON_UNINSTALL) {</code><br> -<code>console.log('really uninstalling');</code><br> -<code>} else {</code><br> -<code>console.log('not a permanent uninstall, likely an upgrade or downgrade');</code><br> -<code>}</code><br> -<code>}</code></div> - -<pre>void uninstall( - data, - reason -); -</pre> - -<h6 id="Parameters_4">Parameters</h6> - -<dl> - <dt><code>data</code></dt> - <dd>A <a href="#Bootstrap_data">bootstrap data structure</a>.</dd> - <dt><code>reason</code></dt> - <dd>One of the <a href="#Reason_constants">reason constants</a>, indicating why the extension is being uninstalled. This will be one of <code>ADDON_UNINSTALL</code>, <code>ADDON_UPGRADE</code>, or <code>ADDON_DOWNGRADE</code>.</dd> -</dl> - -<h2 id="Reason_constants">Reason constants</h2> - -<p>The bootstrap functions accept a <code>reason</code> parameter, which explains to the extension why it's being called. The reason constants are:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">Constant</td> - <td class="header">Value</td> - <td class="header">Description</td> - </tr> - <tr> - <td><code>APP_STARTUP</code></td> - <td>1</td> - <td>The application is starting up.</td> - </tr> - <tr> - <td><code>APP_SHUTDOWN</code></td> - <td>2</td> - <td>The application is shutting down.</td> - </tr> - <tr> - <td><code>ADDON_ENABLE</code></td> - <td>3</td> - <td>The add-on is being enabled.</td> - </tr> - <tr> - <td><code>ADDON_DISABLE</code></td> - <td>4</td> - <td>The add-on is being disabled. (Also <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=620541">sent during uninstallation</a>)</td> - </tr> - <tr> - <td><code>ADDON_INSTALL</code></td> - <td>5</td> - <td>The add-on is being installed.</td> - </tr> - <tr> - <td><code>ADDON_UNINSTALL</code></td> - <td>6</td> - <td>The add-on is being uninstalled.</td> - </tr> - <tr> - <td><code>ADDON_UPGRADE</code></td> - <td>7</td> - <td>The add-on is being upgraded.</td> - </tr> - <tr> - <td><code>ADDON_DOWNGRADE</code></td> - <td>8</td> - <td>The add-on is being downgraded.</td> - </tr> - </tbody> -</table> - -<h2 id="Bootstrap_data">Bootstrap data</h2> - -<p>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 <code><a href="/en-US/docs/Addons/Add-on_Manager/AddonManager#getAddonByID()">AddonManager.getAddonByID()</a></code>. The data is a simple JavaScript object with the following properties:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">Property</td> - <td class="header">Type</td> - <td class="header">Description</td> - </tr> - <tr> - <td><code>id</code></td> - <td><code>string</code></td> - <td>The ID of the add-on being bootstrapped.</td> - </tr> - <tr> - <td><code>version</code></td> - <td><code>string</code></td> - <td>The version of the add-on being bootstrapped.</td> - </tr> - <tr> - <td><code>installPath</code></td> - <td><code>nsIFile</code></td> - <td>The installation location of the add-on being bootstrapped. This may be a directory or an XPI file depending on whether the add-on is installed unpacked or not.</td> - </tr> - <tr> - <td><code>resourceURI</code></td> - <td><code>nsIURI</code></td> - <td>A URI pointing at the root of the add-ons files, this may be a <code>jar:</code> or <code>file:</code> URI depending on whether the add-on is installed unpacked or not. {{ gecko_minversion_inline("7.0") }}</td> - </tr> - <tr> - <td><code>oldVersion</code></td> - <td><code>string</code></td> - <td>The previously installed version, if the reason is <code>ADDON_UPGRADE</code> or <code>ADDON_DOWNGRADE</code>, and the method is <code>install</code> or <code>startup</code>. {{ gecko_minversion_inline("22.0") }}</td> - </tr> - <tr> - <td><code>newVersion</code></td> - <td><code>string</code></td> - <td>The version to be installed, if the reason is <code>ADDON_UPGRADE</code> or <code>ADDON_DOWNGRADE</code>, and the method is <code>shutdown</code> or <code>uninstall</code>. {{ gecko_minversion_inline("22.0") }}</td> - </tr> - </tbody> -</table> - -<div class="note"> -<p><strong>Note:</strong> An add-on may be upgraded/downgraded at application startup, in this case the <code>startup</code> method reason is <code>APP_STARTUP</code>, and the <code>oldVersion</code> property is not set. Also be aware that in some circumstances an add-on upgrade/downgrade may occur without the <code>uninstall</code> method being called.</p> -</div> - -<h2 id="Add-on_debugger">Add-on debugger</h2> - -<p>From Firefox 31 onwards, you can use the <a href="/en-US/Add-ons/Add-on_Debugger">Add-on Debugger</a> to debug bootstrapped add-ons.</p> - -<h2 id="Localization_(L10n)">Localization (L10n)</h2> - -<p>Localizing bootstrapped add-ons is very much the same since Firefox 7, as that is when chrome.manifest compatibility landed.</p> - -<h3 id="JS_and_JSM_Files_-_Using_Property_Files">JS and JSM Files - Using Property Files</h3> - -<p>To localize your .js and .jsm files you have to use <a href="/en-US/docs/XUL/Tutorial/Property_Files">property files</a>.</p> - -<p>The absolute minimum needed here is:</p> - -<ol> - <li>File: install.rdf</li> - <li>File: chrome.manifest</li> - <li>File: bootstrap.js</li> - <li>Folder: locale - <ol> - <li>Folder: VALID_LOCALE_HERE - <ol> - <li>File: ANYTHING.properties</li> - </ol> - </li> - </ol> - </li> -</ol> - -<p>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: <code>locale NAME_OF_YOUR_ADDON en-US locale/en-US/</code></p> - -<p>Here is an example: <a href="https://github.com/Noitidart/l10n/tree/properties">GitHub :: l10n-properties</a> - 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.</p> - -<h3 id="XUL_and_HTML_Files_-_Using_Entities_from_DTD_Files">XUL and HTML Files - Using Entities from DTD Files</h3> - -<p>Many times HTML pages are used, however they cannot be localized with DTD files. There are three changes you must make:</p> - -<ol> - <li>You have to change the HTML file's extension to be <code>.xhtml</code></li> - <li>The doctype must be defined point to a DTD file in your locale folder such as: <code><!DOCTYPE html SYSTEM <span class="pl-s1">"chrome://l10n/locale/mozilla.dtd"</span>></code></li> - <li>Must add xmlns attribute to html tag for example: <code><<span class="pl-ent">html</span> <span class="pl-e">xmlns</span>=<span class="pl-s1"><span class="pl-pds">"</span>http://www.w3.org/1999/xhtml<span class="pl-pds">"</span></span>></code></li> - <li>If you have multiple DTD files read on here: <a href="/en-US/docs/Using_multiple_DTDs">Using multiple DTDs</a></li> -</ol> - -<p>The bare minimum needed is:</p> - -<ol> - <li>File: install.rdf</li> - <li>File: chrome.manifest</li> - <li>File: bootstrap.js</li> - <li>Folder: locale - <ol> - <li>Folder: VALID_LOCALE_HERE - <ol> - <li>File: ANYTHING.dtd</li> - </ol> - </li> - </ol> - </li> -</ol> - -<p>The chrome.manifest file must include a definition for content for example: <code>content NAME_OF_YOUR_ADDON ./</code></p> - -<p>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: <code>locale NAME_OF_YOUR_ADDON en-US locale/en-US/</code></p> - -<p>Here is an example add-on that opens an HTML page and a XUL page on install: <a href="https://github.com/Noitidart/l10n/tree/c456cc82a8a66b6d552cd8c2299cd2babc383af0">GitHub :: l10n-xhtml-xul</a>. Here is an example showing how to use a localized HTML page as an options page: <a href="https://github.com/Noitidart/l10n/tree/html-options">GitHub :: l10n-html-options</a>. You can go to about:config and change the value of the preference <code>general.useragent.locale </code>to <code>en-US</code> and then to <code>en-GB</code> and then reload the open pages to see the localization change.</p> - -<h2 id="Further_reading">Further reading</h2> - -<ul> - <li><a href="https://developer.mozilla.org/en-US/Add-ons/How_to_convert_an_overlay_extension_to_restartless">How to convert an overlay extension to restartless</a> a step by step guide. Some code samples are provided. The page is based on and expanded from Dave Garrett's step-by-step guide to <a class="external" href="https://flagfox.wordpress.com/2014/01/19/writing-restartless-addons/">convert an old overlay based extension into a restartless addon</a>.</li> - <li>Dave Townsend provides a basic code base to <a class="external" href="http://www.oxymoronical.com/blog/2011/01/Playing-with-windows-in-restartless-bootstrapped-extensions">load UI for each opened window</a> in a bootstrapped extension.</li> - <li>Mark Finkle provides some simple example code for <a class="external" href="http://starkravingfinkle.org/blog/2011/01/bootstrap-jones-adventures-in-restartless-add-ons/">restartless add-ons in mobile Firefox</a>, <a class="external" href="http://starkravingfinkle.org/blog/2011/01/restartless-add-ons-more-resources/">adding resources (like the options window)</a> to bootstrapped extensions and <a class="external" href="http://starkravingfinkle.org/blog/2011/01/restartless-add-ons-%e2%80%93-default-preferences/">using default preferences</a> without a <code>default/preferences/prefs.js</code> file.</li> - <li>Kris Maglione writes about <a class="external" href="http://maglione-k.users.sourceforge.net/bootstrapped.xhtml">the requirements for the cleanup procedures</a> in bootstrapped extensions.</li> - <li>Edward Lee shows off some <a class="external" href="http://ed.agadak.net/2011/01/restartless-add-on-example-code">helpful coding patterns and examples</a> you can use in your bootstrapped add-on.</li> - <li>Documentation for <a href="/en-US/docs/Extensions/Inline_Options">Inline Options</a> in Firefox 7 and later.</li> -</ul> diff --git a/files/ru/mozilla/add-ons/рекомендации_по_повышению_производительности_расширений/index.html b/files/ru/mozilla/add-ons/рекомендации_по_повышению_производительности_расширений/index.html deleted file mode 100644 index 4442856118..0000000000 --- a/files/ru/mozilla/add-ons/рекомендации_по_повышению_производительности_расширений/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Рекомендации по повышению производительности расширений -slug: Mozilla/Add-ons/Рекомендации_по_повышению_производительности_расширений -tags: - - Быстродействие - - Лучшие практики - - Плагины - - Производительность - - Расширения - - Руководство -translation_of: Archive/Add-ons/Performance_best_practices_in_extensions ---- -<p>Одно из самых значительных преимуществ браузера Firefox заключается в его чрезвычайной расширяемости. Благодаря дополнениям можно сделать практически что угодно. Есть и обратная сторона медали: плохо написанные расширения могут оказывать серьезное влияние на просмотр сайтов, в том числе и на производительность браузера Firefox в целом. Эта статья предлагает вашему вниманию лучшие практики и рекомендации, которые позволят повысить производительность и быстродействие не только вашего расширения, но также и самого браузера Firefox.</p> - -<h2 id="Увеличиваем_скорость_запуска">Увеличиваем скорость запуска</h2> - -<p>Расширения загружаются и выполняются всякий раз, когда открывается новое окно браузера. Это значит, что при каждом открытии окна ваше расширение может задерживать вывод желаемого контента на экран. Есть несколько способов уменьшения времени задержки вывода пользовательского контента.</p> - -<h3 id="Загружайте_только_то_что_вам_действительно_требуется">Загружайте только то, что вам действительно требуется</h3> - -<p>В момент запуска плагина не следует загружать то, что понадобится только после нажатия пользователем на кнопку, или то, что понадобится только при включенной опции, если сейчас она выключена. Если ваше расширение предоставляет функции, доступные только после авторизации пользователя в сервисе, не следует загружать ресурсы для этих функций до тех пор, пока пользователь фактически не пройдет процедуру авторизации.</p> - -<h3 id="Используйте_модули_JavaScript">Используйте модули JavaScript</h3> - -<p>Вы можете создать собственный <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Using" title="/en-US/docs/Mozilla/JavaScript_code_modules/Using">модуль JavaScript</a>, объединив набор функций, которые нужны только в определенных ситуациях. Это упростит загрузку блоков кода вашего расширения на лету, вместо загрузки всего сразу.</p> - -<p>Несмотря на то, что модули JavaScript могут быть чрезвычайно полезны и давать прирост производительности, они должны применяться разумно. Загрузка модулей все же несет небольшие затраты, поэтому разбивка кода на ненужные уровни может привести к негативным результатам. Код должен быть разбит на модули так, чтобы от этого улучшалась его понятность, а загрузка крупных или требующих больших затрат блоков кода могла быть значительно отсрочена.</p> - -<h3 id="Отсрочивайте_все_что_возможно">Отсрочивайте все, что возможно</h3> - -<p>У большинства расширений есть обработчик события загрузки в главном оверлее, который выполняет функцию при запуске браузера. Выполняйте в этой функции как можно меньше кода. Окно браузера зависает до тех пор, пока обработчик загрузки вашего плагина полностью не выполнится, поэтому чем больше в нем осуществляется действий, тем медленнее Firefox кажется пользователю.</p> - -<p>Если что-то можно сделать пусть даже на долю секунды позже, используйте методы {{ interface("nsITimer") }} или {{ domxref("window.setTimeout()") }} для того, чтобы отложить это действие на потом. Даже короткая отсрочка может иметь большое влияние на быстродействие.</p> - -<h2 id="Общие_вопросы_производительности">Общие вопросы производительности</h2> - -<h3 id="Избегайте_утечек_памяти">Избегайте утечек памяти</h3> - -<p>Утечки памяти вынуждают сборщик мусора и сборщик циклических ссылок (cycle collector) выполнять больший объем работы, а это в значительной мере сказывается на быстродействии.</p> - -<p>Зомби-ячейки (zombie compartments) - это особый вид утечки памяти, который можно легко выявить. Загляните на страницу<a href="/en/Zombie_compartments" title="en/Zombie_compartments"> </a><a href="/en/Zombie_compartments" title="en/Zombie_compartments">Зомби-ячейки</a>, особенно раздел <a href="/en/Zombie_compartments#Proactive_checking_of_add-ons" title="en/Zombie_compartments#Proactive_checking_of_add-ons">Проактивная проверка плагинов</a>.</p> - -<p>Ознакомьтесь с разделом <a href="/en/Extensions/Common_causes_of_memory_leaks_in_extensions" title="en/Extensions/Common_causes_of_zombie_compartments_in_extensions">Распространенные причины утечек памяти в расширениях</a>, чтобы узнать, как избежать возникновения зомби-ячеек и других видов утечек.</p> - -<p>Помимо поиска различных видов утечек памяти, стоит также проверить функционал вашего расширения и содержимое вкладки about:memory на предмет избыточного потребления памяти. Например, <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=719601" title="https://bugzilla.mozilla.org/show_bug.cgi?id=719601">ошибка 719601</a> приводила к тому, что ячейка JavaScript содержала сотни мегабайт памяти, что гораздо больше, чем обычно.</p> - -<h3 id="Избегайте_написания_медленных_таблиц_стилей_CSS">Избегайте написания медленных таблиц стилей CSS</h3> - -<ul> - <li>Прочитайте руководство <a href="/en/CSS/Writing_Efficient_CSS" title="en/CSS/Writing_Efficient_CSS">"Разработка эффективных таблиц стилей CSS"</a>.</li> - <li>Помните, что каждый селектор в вашем правиле, который может совпадать с множеством различных узлов - это источник снижения производительности при поиске совпадения или выполнении динамического обновления элемента. Это особенно плохо, если селектор может динамически запускать и останавливать поиск совпадений. Остерегайтесь использования псевдо-класса ":hover".</li> -</ul> - -<h3 id="Избегайте_использования_технологии_DOM_Mutation_Events">Избегайте использования технологии DOM Mutation Events</h3> - -<p>Технология прослушивания изменений DOM чрезвычайно затратна по ресурсам, ее использование приводит к значительному ухудшению быстродействия. Так как она официально признана нерекомендуемой для применения, при этом имеется <a href="/en-US/Add-ons/Overlay_Extensions/XUL_School/Appendix_F:_Monitoring_DOM_changes">множество аналогов</a>, ее следует всячески избегать.</p> - -<h3 id="Используйте_методы_ленивой_загрузки">Используйте методы ленивой загрузки</h3> - -<p><a href="/en/JavaScript_code_modules/XPCOMUtils.jsm#Methods" title="en/JavaScript_code_modules/XPCOMUtils.jsm#Methods">JavaScript-модуль XPCOMUtils</a> предоставляет два метрода ленивой (отложенной) загрузки:</p> - -<ul> - <li><code>defineLazyGetter()</code> определяет для указанного объекта функцию, которая действует как метод доступа get, возвращающий объект, который будет создан в момент первого обращения к нему. <a class="external" href="http://mxr.mozilla.org/mozilla-central/search?string=defineLazyGetter">Подробнее см. примеры</a>.</li> - <li><code>defineLazyServiceGetter()</code> определяет для указанного объекта функцию, которая действует как метод доступа get для сервиса. Сервис не будет получен до первого его использования. Например, {{ LXRSearch("ident", "string", "defineLazyServiceGetter", "Look through the source") }}.</li> -</ul> - -<p>Множество распространенных сервисов уже закэшированы для вас в модуле <a href="/en-US/JavaScript_code_modules/Services.jsm">Services.jsm</a>.</p> - -<h3 id="Используйте_ассинхронный_вводвывод">Используйте ассинхронный ввод/вывод</h3> - -<p>Это следует подчеркнуть: никогда не выполняйте синхронный ввод/вывод в главном потоке.</p> - -<p>Любой ввод/вывод в главном потоке, будь то активность жесткого диска или сетевая активность, может стать причиной серьезных проблем с временем отклика интерфейса пользователя.</p> - -<ul> - <li>Никогда не используйте синхронные запросы XMLHttpRequests.</li> - <li>Используйте модуль <a href="/en-US/JavaScript_code_modules/NetUtil.jsm">NetUtils.jsm</a>, который предоставляет возможность асинхронного чтения и копирования файлов.</li> - <li>Никогда не работайте с базами данных SQLite синхронно. Вместо этого используйте <a href="/en-US/Storage#Asynchronously">асинхронный API</a>.</li> - <li>Выполняясь одна за другой, асинхронные операции зачастую можно значительно упростить, используя объект <a href="/en-US/Add-ons/Techniques/Promises">Promises</a>.</li> -</ul> - -<h3 id="Избегайте_событий_перемещения_мыши">Избегайте событий перемещения мыши</h3> - -<p>Избегайте использования обработчиков событий мыши, включая такие события, как mouseover, mouseout, mouseenter, mouseexit, и особенно mousemove. Они возникают довольно часто, поэтому их обработчики способны в значительной мере повысить нагрузку на процессор.</p> - -<p>Когда без них обойтись не получается, во время обработки события должен выполняться минимум вычислений, а существенная работа приостановлена. Обработчики должны добавляться к наиболее вероятному элементу, и удаляться, если непосредственно не требуются в данный момент.</p> - -<h3 id="Избегайте_анимированных_изображений">Избегайте анимированных изображений</h3> - -<p>Анимированные изображения значительно более ресурсозатратны, чем считалось ранее, особенно когда используются в элементах {{ XULElem("tree") }}.</p> - -<h3 id="Рассмотрите_возможность_применения_Chrome_Workers">Рассмотрите возможность применения Chrome Workers</h3> - -<p>Вы можете использовать {{ domxref("ChromeWorker") }} для выполнения длительных задач или обработки данных.</p> - -<h2 id="Смотрите_также">Смотрите также</h2> - -<ul> - <li><a href="/en/Performance/Measuring_add-on_startup_performance" title="en/Measuring Add-on Startup Performance">Измерение скорости запуска дополнения</a></li> - <li><a class="external" href="http://blog.mozilla.com/addons/2010/06/14/improve-extension-startup-performance/" title="http://blog.mozilla.com/addons/2010/06/14/improve-extension-startup-performance/">How to Improve Extension Startup Performance</a></li> - <li><a href="/en-US/docs/Performance">Общая информация об измерении и повышении производительности</a></li> -</ul> |