diff options
Diffstat (limited to 'files/ru/mozilla/add-ons/sdk')
22 files changed, 0 insertions, 4250 deletions
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> |