From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../add-ons/sdk/high-level_apis/base64/index.html | 111 +++ .../sdk/high-level_apis/context-menu/index.html | 833 +++++++++++++++++++++ .../mozilla/add-ons/sdk/high-level_apis/index.html | 13 + .../sdk/high-level_apis/indexed-db/index.html | 166 ++++ .../sdk/high-level_apis/simple-storage/index.html | 170 +++++ .../add-ons/sdk/high-level_apis/tabs/index.html | 669 +++++++++++++++++ files/fr/mozilla/add-ons/sdk/index.html | 337 +++++++++ .../mozilla/add-ons/sdk/low-level_apis/index.html | 24 + .../sdk/low-level_apis/io_byte-streams/index.html | 109 +++ .../add-ons/sdk/low-level_apis/io_file/index.html | 196 +++++ .../low-level_apis/system_child_process/index.html | 50 ++ .../sdk/low-level_apis/ui_button_action/index.html | 659 ++++++++++++++++ .../add-ons/sdk/tools/cfx_to_jpm/index.html | 192 +++++ files/fr/mozilla/add-ons/sdk/tools/index.html | 13 + files/fr/mozilla/add-ons/sdk/tools/jpm/index.html | 600 +++++++++++++++ .../tutorials/add_a_context_menu_item/index.html | 115 +++ .../sdk/tutorials/getting_started_(jpm)/index.html | 165 ++++ files/fr/mozilla/add-ons/sdk/tutorials/index.html | 143 ++++ .../mozilla/add-ons/sdk/tutorials/l10n/index.html | 383 ++++++++++ 19 files changed, 4948 insertions(+) create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/base64/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/indexed-db/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/simple-storage/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/high-level_apis/tabs/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/low-level_apis/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/low-level_apis/io_byte-streams/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/low-level_apis/io_file/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/low-level_apis/system_child_process/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/low-level_apis/ui_button_action/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tools/cfx_to_jpm/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tools/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tools/jpm/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tutorials/add_a_context_menu_item/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tutorials/index.html create mode 100644 files/fr/mozilla/add-ons/sdk/tutorials/l10n/index.html (limited to 'files/fr/mozilla/add-ons/sdk') diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/base64/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/base64/index.html new file mode 100644 index 0000000000..f4d71166d9 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/base64/index.html @@ -0,0 +1,111 @@ +--- +title: base64 +slug: Mozilla/Add-ons/SDK/High-Level_APIs/base64 +translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/base64 +--- +

 Le codage des données et le décodage en utilisant des algorithmes Base64.
+
+ var base64 = require ("sdk / base64");
+  
+ var encodedData = base64.encode ("Bonjour, monde»);
+ var decodedData = base64.decode (encodedData);

+ +
+
Les fonctions
+encode (données, charset)
+
+Crée une chaîne de caractères ASCII de base 64 codé à partir d'une chaîne de données binaires.
+Paramètres
+
+données: string
+Les données pour coder
+
+charset: string
+Le charset de la chaîne à coder (en option). La seule valeur acceptée est "utf-8". Pour coder et décoder les chaînes Unicode, le paramètre charset doit être réglé:
+
+var base64 = require ("sdk / base64");
+
+var encodedData = base64.encode (UnicodeString, "utf-8");
+
+résultats
+
+string: La chaîne codée
+decode (données, charset)
+
+Décode une chaîne de données qui a été codé en utilisant la base 64 codage.
+Paramètres
+
+données: string
+Les données codées
+
+charset: string
+Le charset de la chaîne à coder (en option). La seule valeur acceptée est "utf-8". Pour coder et décoder les chaînes Unicode, le paramètre charset doit être réglé:
+
+var base64 = require ("sdk / base64");
+
+var decodedData = base64.decode (encodedData, "utf-8");
+
+résultats
+
+string: La chaîne décodée (encodedData);
+
+ +
+

{{AddonSidebar}}

+
+ +
+

Unstable

+
+ +

Data encoding and decoding using Base64 algorithms.

+ +
var base64 = require("sdk/base64");
+
+var encodedData = base64.encode("Hello, World");
+var decodedData = base64.decode(encodedData);
+ +

Globals

+ +

Functions

+ +

encode(data, charset)

+ +

Creates a base-64 encoded ASCII string from a string of binary data.

+ +
Parameters
+ +

data : string
+ The data to encode

+ +

charset : string
+ The charset of the string to encode (optional). The only accepted value is "utf-8". In order to encode and decode Unicode strings, the charset parameter needs to be set:

+ +
var base64 = require("sdk/base64");
+
+var encodedData = base64.encode(unicodeString, "utf-8");
+
+ +
Returns
+ +

string : The encoded string

+ +

decode(data, charset)

+ +

Decodes a string of data which has been encoded using base-64 encoding.

+ +
Parameters
+ +

data : string
+ The encoded data

+ +

charset : string
+ The charset of the string to encode (optional). The only accepted value is "utf-8". In order to encode and decode Unicode strings, the charset parameter needs to be set:

+ +
var base64 = require("sdk/base64");
+
+var decodedData = base64.decode(encodedData, "utf-8");
+ +
Returns
+ +

string : The decoded string

diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html new file mode 100644 index 0000000000..9af486cc64 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/context-menu/index.html @@ -0,0 +1,833 @@ +--- +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 +--- +

{{AddonSidebar}}

+ +
+

Stable

+
+ +

Ajouez des éléments, sous-menus et des séparateurs au menu contextuel.

+ +

Usage

+ +

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

+ +

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

+ +

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

+ +

Specifying contexts

+ +

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

+ +

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

+ +

The page context

+ +

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

+ +

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

+ +

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

+ +

Declarative contexts

+ +

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

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

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

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

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

+ +

In content scripts

+ +

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

+ +

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

+ +

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

+ +

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

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

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

+ +

You can both specify declarative contexts and listen for contexts in a content script. Your context listener is called even if any declarative contexts are not current (since Firefox 36).

+ +

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

+ +

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

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

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

+ +

Handling menu item clicks

+ +

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

+ +

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

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

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

+ +

The "node" argument

+ +

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

+ + + +

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

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

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

+ +

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

+ +
info: contextmenu-example: clicked: BODY
+ +

By contrast, this add-on uses the PageContext:

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

It will log the name of the actual node clicked:

+ +
info: contextmenu-example: clicked: P
+ +

The "data" Argument

+ +

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

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

Communicating With the Add-on

+ +

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

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

Updating a menu item's label

+ +

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

+ +

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

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

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

+ +

This item implements the aforementioned search example:

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

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

+ +

You can also get the selected text using the High Level selection API.

+ +
var selection = require("sdk/selection");
+ +

and within the contentScript, reference the selected text as selection.text

+ +

Private windows

+ +

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

+ +

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

+ +

More examples

+ +

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

+ +
+

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

+ +

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

+
+ +

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

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

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

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

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

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

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

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

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

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

To create sub-menus, one of the items in your main menu must be defined as a menu.

+ +
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 bingItem = cm.Item({
+  label: "Bing",
+  data: "http://www.bing.com/search?q="
+});
+var yahooItem = cm.Item({
+  label: "Yahoo",
+  data: "https://search.yahoo.com/search?p="
+});
+var moreMenu = cm.Menu({
+  label: "More Search",
+  items: [bingItem, yahooItem]
+});
+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, moreMenu]
+});
+ +

If you need a tooltip:

+ +

tooltip

+ +

First you need a dummy menu item that will serve as a trigger and subsequently will add the tooltips to the actual menu items.

+ +

It is easy to find out which menu items are constructed by the addon-sdk module because they have the class addon-context-menu-item. The difficult part it to identify those that belong to your extension.

+ +

One way to achieve this it to utilize the data attribute of Item class constructor, which conveniently maps to the value attribute of the underlying xul element.

+ +

So if data consists of unique prefix and the desired tooltip text, it is just a matter of kicking in the right moment.

+ +
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
+
+var cm = require("sdk/context-menu");
+var uuid = require('sdk/util/uuid').uuid();
+var uuidstr = uuid.number.substring(1,37);
+
+cm.Item({
+  data: uuidstr+"This is a tooltip",
+  label: "Just a tigger, will never show up",
+  contentScript: 'self.on("context", function(){self.postMessage(); return false;})',
+  onMessage: function(){
+    var cmitems = getMostRecentBrowserWindow().document.querySelectorAll(".addon-context-menu-item[value^='"+ uuidstr +"']");
+    for(var i=0; i < cmitems.length; i++)
+      cmitems[i].tooltipText = cmitems[i].value.substring(36);
+  }
+});
+ +

 

+ +

Globals

+ +

Constructors

+ +

Item(options)

+ +

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

+ +
Parameters
+ +

options : object
+ Required options:

+ + + + + + + + + + + + + + + + +
NameType 
labelstring +

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

+
+ +

Optional options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
imagestring +

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

+
datastring +

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

+
accesskeysingle-character string +
+

New in Firefox 35.

+
+ +

Access key for the item. Pressing this key selects the item when the context menu is open.

+
contextvalue +

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

+
contentScriptstring,array +

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

+
contentScriptFilestring,array +

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

+
onMessagefunction +

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

+
+ + + +

Creates a labeled menu item that expands into a submenu.

+ +
Parameters
+ +

options : object
+ Required options:

+ + + + + + + + + + + + + + + + + + + + + +
NameType 
labelstring +

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

+
itemsarray +

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

+
+ +

Optional options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
imagestring +

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

+
contextvalue +

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

+
contentScriptstring,array +

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

+
contentScriptFilestring,array +

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

+
onMessagefunction +

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

+
+ +

Separator()

+ +

Creates a menu separator.

+ +

PageContext()

+ +

Creates a page context. See Specifying Contexts above.

+ +

SelectionContext()

+ +

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

+ +

SelectorContext(selector)

+ +

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

+ +
Parameters
+ +

selector : string
+ A CSS selector.

+ +

URLContext(matchPattern)

+ +

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

+ +
Parameters
+ +

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

+ +

PredicateContext(predicateFunction)

+ +
+

New in Firefox 29

+
+ +

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

+ +
Parameters
+ +

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

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

Item

+ +

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

+ +

Methods

+ +

destroy()

+ +

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

+ +

Properties

+ +

label

+ +

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

+ +

image

+ +

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

+ +

data

+ +

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

+ +

context

+ +

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

+ +

parentMenu

+ +

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

+ +

contentScript

+ +

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

+ +

contentScriptFile

+ +

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

+ +

Events

+ +

message

+ +

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

+ +
Arguments
+ +

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

+ + + +

A labeled menu item that expands into a submenu.

+ +

Methods

+ +

addItem(item)

+ +

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

+ +
Parameters
+ +

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

+ +

removeItem(item)

+ +

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

+ +
Parameters
+ +

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

+ +

destroy()

+ +

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

+ +

Properties

+ +

label

+ +

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

+ +

items

+ +

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

+ +

image

+ +

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

+ +

context

+ +

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

+ +

parentMenu

+ +

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

+ +

contentScript

+ +

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

+ +

contentScriptFile

+ +

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

+ +

Events

+ +

message

+ +

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

+ +
Arguments
+ +

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

+ +

Separator

+ +

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

+ +

Methods

+ +

destroy()

+ +

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

+ +

Properties

+ +

parentMenu

+ +

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

diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/index.html new file mode 100644 index 0000000000..e78b5f5cb5 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/index.html @@ -0,0 +1,13 @@ +--- +title: High-Level APIs +slug: Mozilla/Add-ons/SDK/High-Level_APIs +tags: + - Add-on SDK + - TopicStub +translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs +--- +

{{AddonSidebar}}

+ +

Les modules répertoriés sur cette page implémentent des API de haut niveau pour la création de modules complémentaires: création d'interfaces utilisateur, interaction avec le Web et interaction avec le navigateur.

+ +

Sauf indication contraire explicite de la documentation, tous ces modules sont "Stables": nous éviterons d'y apporter des modifications incompatibles. {{ LandingPageListSubpages ("/en-US/Add-ons/SDK/High-Level_APIs", 5) }}

diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/indexed-db/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/indexed-db/index.html new file mode 100644 index 0000000000..4a73e29e98 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/indexed-db/index.html @@ -0,0 +1,166 @@ +--- +title: indexed-db +slug: Mozilla/Add-ons/SDK/High-Level_APIs/indexed-db +translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/indexed-db +--- +

{{AddonSidebar}}

+ +
+

Expérimental

+
+ +

Expose l'API IndexedDB pour les add-ons.

+ +

Utilisation

+ +

Les scripts en cours d'exécution dans les pages Web peuvent accéder à IndexedDB via window. Par exemple:

+ +
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
+
+var request = window.indexedDB.open("MyDatabase");
+request.onerror = function(event) {
+  console.log("failure");
+};
+request.onsuccess = function(event) {
+  console.log("success");
+};
+ +

Parce que votre code add-on principale ne peut pas accéder au DOM, vous ne pouvez pas faire cela. Mais vous pouvez utiliser le module indexed-db pour y accéder:

+ +
var { indexedDB } = require('sdk/indexed-db');
+
+var request = indexedDB.open('MyDatabase');
+request.onerror = function(event) {
+  console.log("failure");
+};
+request.onsuccess = function(event) {
+  console.log("success");
+};
+ +

La plupart des objets qui mettent en œuvre l'API IndexedDB, tels que IDBTransaction , IDBOpenDBRequest , et IDBObjectStore , sont accessibles à travers l'objet IndexedDB lui-même. < br>

+ +

L'API exposée par indexed-db est presque identique à l'API DOM IndexedDB, donc on n'a pas répété sa documentation ici, référer vous à la documentation de l'API IndexedDB pour tous les détails.

+ +

La base de données créé sera unique et privée pour l'add-on, et n'est pas liés à une base de données de site. Le module ne peut pas être utilisé pour interagir avec une base de données du site donné. Voir bug 778197 et bug 786688 .

+ +

Exemple

+ +
+

Cet exemple utilise l'API bouton d'action , qui est uniquement disponible à partir de Firefox 29 partir.

+
+ +

Voici un add-on complet qui ajoute deux boutons pour le navigateur: le bouton "Ajouter" ajoute le titre de l'onglet en cours à une base de données, tandis que le bouton intitulé «Liste» répertorie tous les titres dans la base de données .

+ +

L'add-on implémente les fonctions open(), addItem() et getItems() pour ouvrir la base de données, ajouter un nouvel élément à la base de données, et d'obtenir tous les éléments de la base de données.

+ +
var { indexedDB, IDBKeyRange } = require('sdk/indexed-db');
+
+var database = {};
+
+database.onerror = function(e) {
+  console.error(e.value)
+}
+
+function open(version) {
+  var request = indexedDB.open("stuff", version);
+
+  request.onupgradeneeded = function(e) {
+    var db = e.target.result;
+    e.target.transaction.onerror = database.onerror;
+
+    if(db.objectStoreNames.contains("items")) {
+      db.deleteObjectStore("items");
+    }
+
+    var store = db.createObjectStore("items",
+      {keyPath: "time"});
+  };
+
+  request.onsuccess = function(e) {
+    database.db = e.target.result;
+  };
+
+  request.onerror = database.onerror;
+};
+
+function addItem(name) {
+  var db = database.db;
+  var trans = db.transaction(["items"], "readwrite");
+  var store = trans.objectStore("items");
+  var time = new Date().getTime();
+  var request = store.put({
+    "name": name,
+    "time": time
+  });
+
+  request.onerror = database.onerror;
+};
+
+function getItems(callback) {
+  var cb = callback;
+  var db = database.db;
+  var trans = db.transaction(["items"], "readwrite");
+  var store = trans.objectStore("items");
+  var items = new Array();
+
+  trans.oncomplete = function() {
+    cb(items);
+  }
+
+  var keyRange = IDBKeyRange.lowerBound(0);
+  var cursorRequest = store.openCursor(keyRange);
+
+  cursorRequest.onsuccess = function(e) {
+    var result = e.target.result;
+    if(!!result == false)
+      return;
+
+    items.push(result.value.name);
+    result.continue();
+  };
+
+  cursorRequest.onerror = database.onerror;
+};
+
+function listItems(itemList) {
+  console.log(itemList);
+}
+
+open("1");
+
+var add = require("sdk/ui/button/action").ActionButton({
+  id: "add",
+  label: "Add",
+  icon: "./add.png",
+  onClick: function() {
+    addItem(require("sdk/tabs").activeTab.title);
+  }
+});
+
+var list = require("sdk/ui/button/action").ActionButton({
+  id: "list",
+  label: "List",
+  icon: "./list.png",
+  onClick: function() {
+    getItems(listItems);
+  }
+});
+
+ +

Notez que pour exécuter cet add-on, vous aurez besoin de fournir des icônes nommées "add.png" et "list.png" dans le répertoire "data" de l'add-ons .

+ +

Globals

+ +

Propriétés

+ +

indexedDB

+ +

Permet de créer, ouvrir et supprimer des bases de données. Voir la documentation IDBFactory.

+ +

IDBKeyRange

+ +

Définit une plage de clés. Voir la documentation IDBKeyRange.

+ +

DOMException

+ +

Fournit des informations plus détaillées sur une exception. Voir la documentation DOMException.

diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/simple-storage/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/simple-storage/index.html new file mode 100644 index 0000000000..2b35fc120b --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/simple-storage/index.html @@ -0,0 +1,170 @@ +--- +title: simple-storage +slug: Mozilla/Add-ons/SDK/High-Level_APIs/simple-storage +translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/simple-storage +--- +

{{AddonSidebar}}

+ +
+

Stable

+
+ +

Permet au add-on le stockage des données afin qu'il soit conservé entre les redémarrages de Firefox. Ce module fonctionne de façon similaire au DOM Storage du Web, mais il est uniquement disponible pour des add-ons.

+ +

Utilisation

+ +

Le module de stockage simple exporte un objet appelé storage qui est persistant et à porté de votre add-on. C'est un objet JavaScript normal, et vous pouvez le traiter comme vous le feriez pour tout autre.

+ +

Pour stocker une valeur, il faut juste l'affecter avec la propriété storage:

+ +
var ss = require("sdk/simple-storage");
+ss.storage.myArray = [1, 1, 2, 3, 5, 8, 13];
+ss.storage.myBoolean = true;
+ss.storage.myNull = null;
+ss.storage.myNumber = 3.1337;
+ss.storage.myObject = { a: "foo", b: { c: true }, d: null };
+ss.storage.myString = "O frabjous day!";
+ +

Vous pouvez stocker des valeurs tableau, booléennes, nombre, objet, null et des textes. Si vous souhaitez stocker d'autres types de valeurs, vous devrez d'abord les convertir en chaînes ou un autre de ces types.

+ +

Veillez à définir les propriétés avec storage et non avec le module lui-même:

+ +
// This is not good!
+var ss = require("sdk/simple-storage");
+ss.foo = "I will not be saved! :(";
+ +

stockage simple et "jpm run"

+ +

Le module de stockage simple stocke ses données dans votre profil. Parce que jpm run utilise par défaut un profil frais chaque fois qu'il est exécuté, le stockage simple ne fonctionnera pas avec des add-ons exécutées en utilisant jpm run - les données stockées ne persisteront pas d'une exécution à l'autre.

+ +

La solution la plus simple à ce problème est d'utiliser l'option --profile de jpm avec un chemin d'accès à un profil - pas seulement un nom de profil. Vous pouvez aussi avoir besoin d'inclure l'option --no-copie pour empêcher Firefox de copier le profil dans un répertoire de temporaire chaque fois qu'il démarre.

+ +
jpm run --no-copy --profile path/to/profile/dir
+ +

Si vous spécifiez un profil non-existant, il sera créé.

+ +
+

Important: Si vous utilisez cette méthode, vous devez mettre fin à votre session de débogage en quittant Firefox normalement, en annulant la commande shell. Si vous ne fermez pas Firefox normalement, puis un simple stockage ne sera pas informé que la session est terminée, et ne sera pas écrire vos données à la mémoire de sauvegarde.

+
+ +

Accès au stockage à partir de la console

+ +

Dans l' Add-on Debugger , vous pouvez accéder à vos addons simple stockage par programmation à partir de la console en utilisant ce qui suit:

+ +
loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage
+ +

Constructeur de tableaux

+ +

Pour ne pas remettre à zéro un tableau, attention au constructeur. Par exemple, cet add-on essaie de stocker les URL des pages visitées:

+ +
var ss = require("sdk/simple-storage");
+ss.storage.pages = [];
+
+require("sdk/tabs").on("ready", function(tab) {
+  ss.storage.pages.push(tab.url);
+});
+
+require("sdk/ui/button/action").ActionButton({
+  id: "read",
+  label: "Read",
+  icon: "./read.png",
+  onClick: function() {
+    console.log(ss.storage.pages);
+  }
+});
+ +

Mais cela ne fonctonne pas, car il vide le tableau chaque fois que l'add-on est apellée (par exemple, chaque fois que Firefox est lancé). La ligne 2 a besoin d'être subordonné, de sorte que le tableau est uniquement construite si il n'existe pas déjà:

+ +
if (!ss.storage.pages)
+  ss.storage.pages = [];
+ +

Suppression de données

+ +

Vous pouvez supprimer des propriétés en utilisant l'opérateur delete. Voici une add-on qui ajoute trois boutons pour écrire, lire et supprimer une valeur:

+ +
var ss = require("sdk/simple-storage");
+
+require("sdk/ui/button/action").ActionButton({
+  id: "write",
+  label: "Write",
+  icon: "./write.png",
+  onClick: function() {
+    ss.storage.value = 1;
+    console.log("Setting value");
+  }
+});
+
+require("sdk/ui/button/action").ActionButton({
+  id: "read",
+  label: "Read",
+  icon: "./read.png",
+  onClick: function() {
+    console.log(ss.storage.value);
+  }
+});
+
+require("sdk/ui/button/action").ActionButton({
+  id: "delete",
+  label: "Delete",
+  icon: "./delete.png",
+  onClick: function() {
+    delete ss.storage.value;
+    console.log("Deleting value");
+  }
+});
+ +

Si vous l'exécutez, vous verrez que si vous cliquez sur "Lire" après avoir cliqué sur "Supprimer" vous aurez le résultat escompté:

+ +
info: undefined
+
+ +

Notez que pour exécuter cet add-on, vous aurez à enregistrer des fichiers icône nommées "write.png", "read.png", et "delete.png" dans le répertoire "data".

+ +

Quotas

+ +

Le stockage simple à la disposition de votre add-on est limité. Actuellement, cette limite est environ cinq mégaoctets (5,242,880 octets). Vous pouvez choisir d'être averti lorsque vous dépassez le quota, et vous devez répondre en réduisant la quantité de données dans le stockage. Si vous quittez l'application pendant que vous êtes hors quota, toutes les données stockées depuis la dernière fois que vous étiez sous le quota ne sont pas conservées. Vous ne devriez pas laisser cela se produire.

+ +

Pour écouter les notifications du quota, utiliser l'evenement "OverQuota". il sera appelée quand votre stockage dépasse le quota.

+ +
function myOnOverQuotaListener() {
+  console.log("Uh oh.");
+}
+ss.on("OverQuota", myOnOverQuotaListener);
+ +

Les auditeurs peuvent également être retirés:

+ +
ss.removeListener("OverQuota", myOnOverQuotaListener);
+ +

Pour connaitre le % de saturation du quota utiliser la proprieté quotaUsage. Si vous êtes dans votre quota, c'est un nombre entre 0 et 1. Si votre add-on utilise plus que son quota, cette valeur est supérieure à 1,0.

+ +

Par conséquent, lorsque vous êtes averti que vous êtes hors quota, vous devez répondre en supprimant les données de l'espace de stockage jusqu'à ce que votre quotaUsage soit inférieur ou égal à 1.

+ +
ss.storage.myList = [ /* some long array */ ];
+ss.on("OverQuota", function () {
+  while (ss.quotaUsage > 1)
+    ss.storage.myList.pop();
+});
+ + + +

Si votre mémoire est liée à l'histoire de vos utilisateurs Web, des renseignements personnels, ou d'autres données sensibles, votre add-on devrait respecter la navigation privé .

+ +

Pour en savoir plus sur la façon de choisir en mode de navigation privée et comment utiliser le SDK pour éviter de stocker des données d'utilisateur associées aux fenêtres privées, reportez-vous à la documentation du private-browsing Module .

+ +

Globals

+ +

Propriétés

+ +

storage

+ +

Un objet persistant privé de votre add-on.

+ +

quotaUsage

+ +

Un certain nombre dans l'intervalle [0, Infinity) qui indique le pourcentage de quota occupé par le stockage. Une valeur dans l'intervalle [0, 1] indique que le stockage est dans le quota. Une valeur supérieure à 1 indique que le stockage dépasse le quota.

+ +

Événements

+ +

OverQuota

+ +

Le module émet cet événement lorsque votre stockage add-ons dépasse son quota.

diff --git a/files/fr/mozilla/add-ons/sdk/high-level_apis/tabs/index.html b/files/fr/mozilla/add-ons/sdk/high-level_apis/tabs/index.html new file mode 100644 index 0000000000..5ffa11d9a4 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/high-level_apis/tabs/index.html @@ -0,0 +1,669 @@ +--- +title: tabs +slug: Mozilla/Add-ons/SDK/High-Level_APIs/tabs +translation_of: Archive/Add-ons/Add-on_SDK/High-Level_APIs/tabs +--- +

{{AddonSidebar}}

+ +
+

Stable

+
+ +

Ouvre, manipule, accède et recevoir les événements des onglets.

+ +

Utilisation

+ +

Ouvrez un onglet

+ +

Vous pouvez ouvrir un nouvel onglet, en spécifiant diverses propriétés, y compris l'emplacement:

+ +
var tabs = require("sdk/tabs");
+tabs.open("http://www.example.com");
+ +

Track tabs

+ +

You can register event listeners to be notified when tabs open, close, finish loading DOM content, or are made active or inactive:

+ +
var tabs = require("sdk/tabs");
+
+// Listen for tab openings.
+tabs.on('open', function onOpen(tab) {
+  myOpenTabs.push(tab);
+});
+
+// Listen for tab content loads.
+tabs.on('ready', function(tab) {
+  console.log('tab is loaded', tab.title, tab.url);
+});
+ +

Access tabs

+ +

The module itself can be used as a list of all opened tabs across all windows. In particular, you can enumerate it:

+ +
var tabs = require('sdk/tabs');
+for (let tab of tabs)
+  console.log(tab.title);
+ +

You can also access individual tabs by index:

+ +
var tabs = require('sdk/tabs');
+
+tabs.on('ready', function () {
+  console.log('first: ' + tabs[0].title);
+  console.log('last: ' + tabs[tabs.length-1].title);
+});
+ +

You can access the currently active tab:

+ +
var tabs = require('sdk/tabs');
+
+tabs.on('activate', function () {
+  console.log('active: ' + tabs.activeTab.url);
+});
+ +

Track a single tab

+ +

Given a tab, you can register event listeners to be notified when the tab is closed, activated or deactivated, or when the page hosted by the tab is loaded or retrieved from the "back-forward cache":

+ +
var tabs = require("sdk/tabs");
+
+function onOpen(tab) {
+  console.log(tab.url + " is open");
+  tab.on("pageshow", logShow);
+  tab.on("activate", logActivate);
+  tab.on("deactivate", logDeactivate);
+  tab.on("close", logClose);
+}
+
+function logShow(tab) {
+  console.log(tab.url + " is loaded");
+}
+
+function logActivate(tab) {
+  console.log(tab.url + " is activated");
+}
+
+function logDeactivate(tab) {
+  console.log(tab.url + " is deactivated");
+}
+
+function logClose(tab) {
+  console.log(tab.url + " is closed");
+}
+
+tabs.on('open', onOpen);
+ +

Manipulate a tab

+ +

You can get and set various properties of tabs (but note that properties relating to the tab's content, such as the URL, will not contain valid values until after the tab's ready event fires). By setting the url property you can load a new page in the tab:

+ +
var tabs = require("sdk/tabs");
+tabs.on('activate', function(tab) {
+  tab.url = "http://www.example.com";
+});
+ +

Run scripts in a tab

+ +

You can attach a content script to the page hosted in a tab, and use that to access and manipulate the page's content (see the Modifying the Page Hosted by a Tab tutorial):

+ +
var tabs = require("sdk/tabs");
+
+tabs.on('activate', function(tab) {
+  var worker = tab.attach({
+    contentScript: 'self.port.emit("html", document.body.innerHTML);'
+  });
+  worker.port.on("html", function(message) {
+    console.log(message)
+  })
+});
+ +

Note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page.

+ +

Attaching stylesheets

+ +
+

New in Firefox 34.

+
+ +

You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod APIs. Here's an add-on that uses a toggle button to attach a stylesheet to the active tab, and detach it again. The stylesheet is called "style.css" and is located in the add-on's "data" directory:

+ +
var tabs = require("sdk/tabs");
+var { attach, detach } = require('sdk/content/mod');
+var { Style } = require('sdk/stylesheet/style');
+var { ToggleButton } = require("sdk/ui/button/toggle");
+
+var style = Style({
+  uri: './style.css'
+});
+
+var button = ToggleButton({
+  id: "stylist",
+  label: "stylist",
+  icon: "./icon-16.png",
+  onChange: function(state) {
+    if (state.checked) {
+      attach(style, tabs.activeTab);
+    }
+    else {
+      detach(style, tabs.activeTab);
+    }
+  }
+});
+ +

Private windows

+ +

If your add-on has not opted into private browsing, then you won't see any tabs that are hosted by private browser windows.

+ +

Tabs hosted by private browser windows won't be seen if you enumerate the tabs module itself, and you won't receive any events for them.

+ +

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

+ +

Converting to XUL tabs

+ +

To convert from the high-level Tab objects used in this API to the low-level XUL tab objects used in the tabs/utils API and by traditional add-ons, use the viewFor() function exported by the viewFor module.

+ +

To convert back the other way, from a XUL tab to a high-level Tab object, use the modelFor() function, exported by the modelFor module.

+ +

Here's an example converting from a high-level Tab to a XUL tab and then back the other way:

+ +
var { modelFor } = require("sdk/model/core");
+var { viewFor } = require("sdk/view/core");
+
+var tabs = require("sdk/tabs");
+var tab_utils = require("sdk/tabs/utils");
+
+function mapHighLevelToLowLevel(tab) {
+  // get the XUL tab that corresponds to this high-level tab
+  var lowLevelTab = viewFor(tab);
+  // now we can, for example, access the tab's content directly
+  var browser = tab_utils.getBrowserForTab(lowLevelTab);
+  console.log(browser.contentDocument.body.innerHTML);
+  // get the high-level tab back from the XUL tab
+  var highLevelTab = modelFor(lowLevelTab);
+  console.log(highLevelTab.url);
+}
+
+tabs.on("ready", mapHighLevelToLowLevel);
+
+ +

Note that directly accessing XUL objects and web content like this means you're no longer protected by the compatibility guarantees made by the SDK's high-level APIs. In particular, your code might not work with multiprocess Firefox.

+ +

Globals

+ +

Functions

+ +

open(options)

+ +

Opens a new tab. The new tab will open in the active window or in a new window, depending on the inNewWindow option.

+ +

Example

+ +
var tabs = require("sdk/tabs");
+
+// Open a new tab on active window and make tab active.
+tabs.open("http://www.mysite.com");
+
+// Open a new tab in a new window and make it active.
+tabs.open({
+  url: "http://www.mysite.com",
+  inNewWindow: true
+});
+
+// Open a new tab on active window in the background.
+tabs.open({
+  url: "http://www.mysite.com",
+  inBackground: true
+});
+
+// Open a new tab as an app tab and do something once it's open.
+tabs.open({
+  url: "http://www.mysite.com",
+  isPinned: true,
+  onOpen: function onOpen(tab) {
+    // do stuff like listen for content
+    // loading.
+  }
+});
+ +
Parameters
+ +

options : object
+ Required options:

+ + + + + + + + + + + + + + + + +
NameType 
urlstring +

String URL to be opened in the new tab. This is a required property.

+
+ +

Optional options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
isPrivateboolean +

Boolean which will determine whether the new tab should be private or not. If your add-on does not support private browsing this will have no effect. See the private-browsing documentation for more information. Defaults to false.

+
inNewWindowboolean +

If present and true, a new browser window will be opened and the URL will be opened in the first tab in that window. This is an optional property.

+
inBackgroundboolean +

If present and true, the new tab will be opened to the right of the active tab and will not be active. This is an optional property.

+
isPinnedboolean +

If present and true, then the new tab will be pinned as an app tab.

+
onOpenfunction +

A callback function that will be registered for the 'open' event. This is an optional property.

+
onClosefunction +

A callback function that will be registered for the 'close' event. This is an optional property.

+
onReadyfunction +

A callback function that will be registered for the 'ready' event. This is an optional property.

+
onLoadfunction +

A callback function that will be registered for the 'load' event. This is an optional property.

+
onPageShowfunction +

A callback function that will be registered for the 'pageshow' event. This is an optional property.

+
onActivatefunction +

A callback function that will be registered for the 'activate' event. This is an optional property.

+
onDeactivatefunction +

A callback function that will be registered for the 'deactivate' event. This is an optional property.

+
+ +

Properties

+ +

activeTab

+ +

The currently active tab in the active window. This property is read-only. To activate a Tab object, call its activate method.

+ +

Example

+ +
// Get the active tab's title.
+var tabs = require("sdk/tabs");
+console.log("title of active tab is " + tabs.activeTab.title);
+ +

length

+ +

The number of open tabs across all windows.

+ +

Events

+ +

open

+ +

This event is emitted when a new tab is opened. This does not mean that the content has loaded, only that the browser tab itself is fully visible to the user.

+ +

Properties relating to the tab's content (for example: title, favicon, and url) will not be correct at this point. If you need to access these properties, listen for the ready event:

+ +
var tabs = require("sdk/tabs");
+tabs.on('open', function(tab){
+  tab.on('ready', function(tab){
+    console.log(tab.url);
+  });
+});
+ +
Arguments
+ +

Tab : Listeners are passed the tab object that just opened.

+ +

close

+ +

This event is emitted when a tab is closed. When a window is closed this event will be emitted for each of the open tabs in that window.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object that has closed.

+ +

ready

+ +

This event is emitted when the DOM for a tab's content is ready. It is equivalent to the DOMContentLoaded event for the given content page.

+ +

A single tab will emit this event every time the DOM is loaded: so it will be emitted again if the tab's location changes or the content is reloaded.

+ +

After this event has been emitted, all properties relating to the tab's content can be used.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object that has loaded.

+ +

activate

+ +

This event is emitted when an inactive tab is made active.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object that has become active.

+ +

deactivate

+ +

This event is emitted when the active tab is made inactive.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object that has become inactive.

+ +

Tab

+ +

A Tab instance represents a single open tab. It contains various tab properties, several methods for manipulation, as well as per-tab event registration.

+ +

Tabs emit all the events described in the Events section. Listeners are passed the Tab object that triggered the event.

+ +

Methods

+ +

pin()

+ +

Pins this tab as an app tab.

+ +

unpin()

+ +

Unpins this tab.

+ +

close(callback)

+ +

Closes this tab.

+ +
Parameters
+ +

callback : function
+ A function to be called when the tab finishes its closing process. This is an optional argument.

+ +

reload()

+ +

Reloads this tab.

+ +

activate()

+ +

Makes this tab active, which will bring this tab to the foreground.

+ +

getThumbnail()

+ +

Returns thumbnail data URI of the page currently loaded in this tab.

+ +

attach(options)

+ +

Attach one or more scripts to the document loaded in the tab. Note that by attaching inside ready event, this becomes tab-centric: if the user navigates to a new page in the same tab, then the content scripts will be reattached to the new page.

+ +

Example

+ +
var tabs = require("sdk/tabs");
+
+tabs.on('ready', function(tab) {
+  var worker = tab.attach({
+      contentScript:
+        'document.body.style.border = "5px solid red";'
+  });
+});
+ +
Parameters
+ +

options : object
+ Optional options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
contentScriptFilestring,array +

The local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. Optional.

+
contentScriptstring,array +

A string or an array of strings of code to be evaluated in the context. Content scripts specified by this option are loaded after those specified by the contentScriptFile option. Optional.

+
contentScriptOptionsobject +

You can use this option to define read-only values for your content scripts.

+ +

The option consists of an object literal listing name:value pairs for the values you want to provide to the content script. For example:

+ +
+// main.js
+
+const tabs = require("sdk/tabs");
+
+tabs.open({
+  url: "./page.html",
+  onReady: function(tab) {
+    tab.attach({
+      contentScriptFile: "./content-script.js",
+      contentScriptOptions: {
+        a: "blah"
+      }
+    });
+  }
+});
+ +

The values are accessible to content scripts via the self.options property:

+ +
+// content-script.js
+
+alert(self.options.a);
+
onMessagefunction +

A function called when the content worker receives a message from content scripts. Listeners are passed a single argument, the message posted from the content script. Optional.

+
onErrorfunctionA function called when the content worker receives an error from content scripts. Listeners are passed a single argument, error, which is the error posted from the content script and an object of type Error. Optional
+ +
Returns
+ +

Worker : The Worker object can be used to communicate with the content script. See Content Scripts guide to learn the details.

+ +

Properties

+ +

id

+ +

The unique id for the tab. This property is read-only.

+ +

title

+ +

The title of the tab (usually the title of the page currently loaded in the tab) This property can be set to change the tab title.

+ +

url

+ +

The URL of the page currently loaded in the tab. This property can be set to load a different URL in the tab.

+ +

favicon

+ +

The URL of the favicon for the page currently loaded in the tab. This property is read-only.

+ +
This property is deprecated. From version 1.15, use the favicon module's getFavicon() function instead.
+ +

contentType

+ +
+

This is currently an experimental API, so we might change it in future releases.

+ +

Returns the MIME type that the document currently loaded in the tab is being rendered as. This may come from HTTP headers or other sources of MIME information, and might be affected by automatic type conversions performed by either the browser or extensions. This property is read-only.

+
+ +

index

+ +

The index of the tab relative to other tabs in the application window. This property can be set to change its relative position.

+ +

isPinned

+ +

Whether or not this tab is pinned as an app tab. This property is read-only.

+ +

window

+ +

The window object for this tab.

+ +

readyState

+ +
+

New in Firefox 33.

+
+ +

A string telling you the load state of the document hosted by this tab. This corresponds directly to Document.readyState. It has one of four possible values:

+ + + +

Once a tab's readyState has entered "interactive", you can retrieve properties such as the document's URL.

+ +

Events

+ +

close

+ +

This event is emitted when the tab is closed. It's also emitted when the tab's window is closed.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

+ +

ready

+ +

This event is emitted when the DOM for the tab's content is ready. It is equivalent to the DOMContentLoaded event for the given content page. At this point the document itself is fully loaded and parsed, but resources such as stylesheets and images may still be loading.

+ +

A single tab will emit this event every time the DOM is loaded: so it will be emitted again if the tab's location changes or the content is reloaded. After this event has been emitted, all properties relating to the tab's content can be used.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

+ +

load

+ +

This event is emitted when the page for the tab's content is loaded. It is equivalent to the load event for the given content page. At this point the document and its resources, such as images and stylesheets, have finished loading.

+ +

This event can be used for pages that do not have a DOMContentLoaded event, like images. For pages that have a DOMContentLoaded event, load is fired after ready.

+ +

A single tab will emit this event every time the page is loaded: so it will be emitted again if the tab's location changes or the content is reloaded. After this event has been emitted, all properties relating to the tab's content can be used.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

+ +

pageshow

+ +

The pageshow event is emitted when the page for a tab's content is loaded. It is equivalent to the pageshow event for the given content page.

+ +

This event is similar to the load and ready events, except unlike load and ready, pageshow is triggered if the page was retrieved from the bfcache. This means that if the user loads a page, loads a new page, then moves back to the previous page using the "Back" button, the pageshow event is emitted when the user moves back to the previous page, while the load and ready events are not.

+ +

This event is not emitted when the tab is made the active tab: to get notified about that, you need to listen to the activate event.

+ +

After this event has been emitted, all properties relating to the tab's content can be used. It is emitted after load and ready.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

+ +

persisted : Listeners are passed a boolean value indicating whether or not the page was loaded from the bfcache.

+ +

activate

+ +

This event is emitted when the tab is made active.

+ +

Note that you cannot guarantee that a tab's content, or even its url, are initialized at the time activate is emitted. This is because when a new tab is opened, its activate event may be emitted before the content is loaded.

+ +

You can use the tab's readyState property to determine whether the tab's content and url will be available: if readyState is uninitialized or loading, then you can't access the tab's properties and must wait for the tab's ready event.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

+ +

deactivate

+ +

This event is emitted when the tab is made inactive.

+ +
Arguments
+ +

Tab : Listeners are passed the tab object.

diff --git a/files/fr/mozilla/add-ons/sdk/index.html b/files/fr/mozilla/add-ons/sdk/index.html new file mode 100644 index 0000000000..4de1603cd2 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/index.html @@ -0,0 +1,337 @@ +--- +title: Add-on SDK +slug: Mozilla/Add-ons/SDK +tags: + - Add-on SDK + - Jetpack +translation_of: Archive/Add-ons/Add-on_SDK +--- +

+ +
+

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

+ +

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

+ +

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

+ +

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

+ +

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to use WebExtensions APIs if they can. See the "Compatibility Milestones" document for more information.

+ +

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

+
+ + + +

+ +

Using the Add-on SDK, you can create Firefox add-ons. You can use various standard Web technologies: JavaScript, HTML, and CSS, to create the add-ons. The SDK includes JavaScript APIs, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.

+ +
+

Tutorials

+ +
+
+
+
Getting started
+
How to install the SDK and use the jpm tool to develop, test, and package add-ons.
+
Interact with the browser
+
Open web pages, listen for pages loading and list open pages.
+
Development techniques
+
Learn about common development techniques, such as unit testing, logging, creating reusable modules, localization, and mobile development.
+
+
+ +
+
+
Create user interface components
+
Create user interface components such as toolbar buttons, context menus, menu items, and dialogs.
+
Modify web pages
+
Modify pages matching a URL pattern or dynamically modify a particular tab.
+
Putting it together
+
Walkthrough of the Annotator example add-on.
+
+
+
+ +
+

Guides

+ +
+
+
+
Contributor's guide
+
Learn how to start contributing to the SDK and about the most important idioms used in the SDK code such as modules, classes and inheritance, private properties, and content processes.
+
SDK infrastructure
+
Aspects of the SDK's underlying technology: modules, the Program ID and the rules defining Firefox compatibility.
+
Content scripts
+
A detailed guide to working with content scripts.
+
+
+ +
+
+
SDK idioms
+
The SDK's event framework and the distinction between add-on scripts and content scripts.
+
XUL migration
+
A guide to porting XUL add-ons to the SDK. This guide includes a comparison of the two toolsets and a working example of porting a XUL add-on.
+
Multiprocess Firefox and the SDK
+
How to check whether your add-on is compatible with multiprocess Firefox or not and fix it accordingly.
+
+
+
+ +
+

Reference

+ +
+
+
+
High-Level APIs
+
Reference documentation for the high-level SDK APIs.
+
Tools reference
+
Reference documentation for the jpm tool used to develop, test and package add-ons, the console global used for logging, and the package.json file.
+
+
+ +
+
+
Low-Level APIs
+
Reference documentation for the low-level SDK APIs.
+
+
+
+ +

+ +
+
+
+
+

Join the Add-on SDK community

+ +
+
Choose your preferred method for joining the discussion:
+ + +
+ +
+ +
+
+
+
diff --git a/files/fr/mozilla/add-ons/sdk/low-level_apis/index.html b/files/fr/mozilla/add-ons/sdk/low-level_apis/index.html new file mode 100644 index 0000000000..0460b4ce3d --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/low-level_apis/index.html @@ -0,0 +1,24 @@ +--- +title: Low-Level APIs +slug: Mozilla/Add-ons/SDK/Low-Level_APIs +tags: + - TopicStub +translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs +--- +

Les modules de cette section implémentent des API de bas niveau. Ces modules se divisent à peu près en trois catégories:

+ + + +

Ces modules sont toujours en développement actif et nous prévoyons d'y apporter des modifications incompatibles dans les prochaines versions.

+ +

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

diff --git a/files/fr/mozilla/add-ons/sdk/low-level_apis/io_byte-streams/index.html b/files/fr/mozilla/add-ons/sdk/low-level_apis/io_byte-streams/index.html new file mode 100644 index 0000000000..c37870a8cb --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/low-level_apis/io_byte-streams/index.html @@ -0,0 +1,109 @@ +--- +title: io/byte-streams +slug: Mozilla/Add-ons/SDK/Low-Level_APIs/io_byte-streams +translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/io_byte-streams +--- +

{{AddonSidebar}}

+ +
+

Expérimental

+
+ +

Fournit des flux d'octets en lecture/écriture.

+ +
function readBinaryDataFromFile (filename) {
+  var fileIO = require("sdk/io/file");
+  var data = null;
+  if (fileIO.exists(filename)) {
+    var ByteReader = fileIO.open(filename, "rb");
+    if (!ByteReader.closed) {
+      data = ByteReader.read();
+      ByteReader.close();
+    }
+  }
+  return data;
+}
+
+ +
function writeBinaryDataToFile(data, filename) {
+  var fileIO = require("sdk/io/file");
+  var ByteWriter = fileIO.open(filename, "wb");
+  if (!ByteWriter.closed) {
+    ByteWriter.write(data);
+    ByteWriter.close();
+  }
+}
+ +

Globals

+ +

Constructeurs

+ +

ByteReader(inputStream)

+ +

Crée un flux d'entrée binaire qui lit les octets d'un flux de support.

+ +

Vous pouvez également créer un objets ByteReader en utilisant la fonction io/file open().

+ +
Paramètres
+ +

inputStream: flux
+ Le flux de support, un nsIInputStream

+ +

ByteWriter(outputStream)

+ +

Crée un flux de sortie binaire qui écrit les octets dans un flux de support.

+ +

Vous pouvez également créer un objets ByteWriter en utilisant la fonction io/file open().

+ +
Parameters
+ +

outputStream : flux
+ Le flux de support, un nsIOutputStream.

+ +

ByteReader

+ +

Méthodes

+ +

close()

+ +

Ferme à la fois le flux et son flux de support. Si le flux est déjà fermé, une exception est levée.

+ +

read(numBytes)

+ +

Lit une chaîne à partir du flux. Si le flux est fermé, une exception est levée.

+ +
Parameters
+ +

numBytes: nombre <être> Le nombre d'octets à lire. Sinon donné, la totalité du flux est lu.

+ +
Retours
+ +

string : Une chaîne contenant les octets lus. Si le flux est finit, retourne une chaîne vide.

+ +

Propriétés

+ +

closed

+ +

Vrai si le flux est fermé.

+ +

ByteWriter

+ +

Méthodes

+ +

close()

+ +

Ferme à la fois le flux et son flux de support. Si le flux est déjà fermé, une exception est levée.

+ +

write(str)

+ +

Ecrit une chaîne dans le flux. Si le flux est fermé, une exception est levée.

+ +
Paramètres
+ +

str: string La chaîne à écrire .

+ +

Propriétés

+ +

closed

+ +

Vrai si le flux est fermé.

diff --git a/files/fr/mozilla/add-ons/sdk/low-level_apis/io_file/index.html b/files/fr/mozilla/add-ons/sdk/low-level_apis/io_file/index.html new file mode 100644 index 0000000000..51900f5799 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/low-level_apis/io_file/index.html @@ -0,0 +1,196 @@ +--- +title: io/file +slug: Mozilla/Add-ons/SDK/Low-Level_APIs/io_file +translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/io_file +--- +

{{AddonSidebar}}

+ +
+

Expérimental

+
+ +

Permet d'accéder au système de fichiers local.

+ +

Utilisation

+ +

Paths

+ +

Les specifications Path de cette API sont spécifiques à l'OS. Cela signifie que les chemins Windows sont spécifiés en utilisant le séparateur antislash (\), et sur les systèmes de type Unix comme Linux et OS X les slash sont utilisés (/).

+ +

To ensure your add-on works for everyone, generate paths using the join function. Unfortunately this API does not currently provide a way to obtain an absolute base path which you could then use with join. For now, you need to require("chrome") and use the XPCOM directory service as described in this article about File I/O.

+ +

Note that if you do decide to hardcode Windows-style paths, be sure to escape backslashes in strings. For example, to specify the file at C:\Users\Myk, you need to use the string "C:\\Users\\Myk", not "C:\Users\Myk".  Read more about escaping characters in strings.

+ +

Globals

+ +

Functions

+ +

basename(path)

+ +
+

The path parameter must be an absolute path, relative paths will cause an error.

+ +

Use the fs/path module for relative path support.

+
+ +

Returns the last component of the given path. For example, basename("/foo/bar/baz") returns "baz". If the path has no components, the empty string is returned.

+ +
Parameters
+ +

path : string
+ The path of a file.

+ +
Returns
+ +

string : The last component of the given path.

+ +

dirname(path)

+ +

Returns the path of the directory containing the given file. If the file is at the top of the volume, the empty string is returned.

+ +
Parameters
+ +

path : string
+ The path of a file.

+ +
Returns
+ +

string : The path of the directory containing the file.

+ +

exists(path)

+ +

Returns true if a file exists at the given path and false otherwise.

+ +
Parameters
+ +

path : string
+ The path of a file.

+ +
Returns
+ +

boolean : True if the file exists and false otherwise.

+ +

join(...)

+ +

Takes a variable number of strings, joins them on the file system's path separator, and returns the result.

+ +
Parameters
+ +

... : strings
+ A variable number of strings to join. The first string must be an absolute path.

+ +
Returns
+ +

string : A single string formed by joining the strings on the file system's path separator.

+ +

list(path)

+ +

Returns an array of file names in the given directory.

+ +
Parameters
+ +

path : string
+ The path of the directory.

+ +
Returns
+ +

array : An array of file names. Each is a basename, not a full path.

+ +

mkpath(path)

+ +

Makes a new directory named by the given path. Any subdirectories that do not exist are also created. mkpath can be called multiple times on the same path.

+ +
Parameters
+ +

path : string
+ The path to create.

+ +

open(path, mode)

+ +

Returns a stream providing access to the contents of a file.

+ +
Parameters
+ +

path : string
+ The path of the file to open.

+ +

mode : string
+ An optional string, each character of which describes a characteristic of the returned stream.

+ + + +

If mode is not given, "r" is assumed, and the file is opened in read-only text mode.

+ +

Apart from these options, this API always passes the following options:  CREATE_FILE, TRUNCATE (see https://dxr.mozilla.org/mozilla-central/source/nsprpub/pr/include/prio.h#550). This means that:

+ + + +
Returns
+ +

stream : If the file is opened in text read-only mode, a TextReader is returned, and if text write-only mode, a TextWriter is returned. See text-streams for information on these text stream objects. If the file is opened in binary read-only mode, a ByteReader is returned, and if binary write-only mode, a ByteWriter is returned. See byte-streams for more information on these byte stream objects. Opened files should always be closed after use by calling close on the returned stream.

+ +

read(path, mode)

+ +

Opens a file and returns a string containing its entire contents.

+ +
Parameters
+ +

path : string
+ The path of the file to read.

+ +

mode : string
+ An optional string, each character of which describes a characteristic of the returned stream. If the string contains "b", the contents will be returned in binary mode. If "b" is not present or mode is not given, the file contents will be returned in text mode.

+ +
Returns
+ +

string : A string containing the file's entire contents.

+ +

remove(path)

+ +

Removes a file from the file system. To remove directories, use rmdir.

+ +
Parameters
+ +

path : string
+ The path of the file to remove.

+ +

rmdir(path)

+ +

Removes a directory from the file system. If the directory is not empty, an exception is thrown.

+ +
Parameters
+ +

path : string
+ The path of the directory to remove.

+ +

isFile(path)

+ +

Returns true only if this path specifies a file.

+ +
const fileIO = require("sdk/io/file");
+
+let path = "/Users/Work/";
+let list = fileIO.list(path);
+
+for (i = 0; i < list.length; i++) {
+  let item = fileIO.join(path, list[i]);
+  if (fileIO.isFile(item)) {
+    console.log(item + " is a file");
+  }
+  else {
+    console.log(item + " is a directory");
+  }
+}
+ +
Parameters
+ +

path : string
+ The path of the object.

diff --git a/files/fr/mozilla/add-ons/sdk/low-level_apis/system_child_process/index.html b/files/fr/mozilla/add-ons/sdk/low-level_apis/system_child_process/index.html new file mode 100644 index 0000000000..9c315edd9f --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/low-level_apis/system_child_process/index.html @@ -0,0 +1,50 @@ +--- +title: system/child_process +slug: Mozilla/Add-ons/SDK/Low-Level_APIs/system_child_process +translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/system_child_process +--- +
+

Expérimentale

+
+ +

Une mise en œuvre de l'API node.js child_process.

+ +

Ce module vous permet d'exécuter un programme sous-jacent dans un nouveau processus. Il émule l'API node.js child_process, qui n'est pas documentées séparément. Cependant, il ya quelques différences :

+ + + +

Voici un exemple qui adapte l'exemple de la documentation de node.js pour spawn() :

+ +
var child_process = require("sdk/system/child_process");
+
+var ls = child_process.spawn('/bin/ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', function (data) {
+  console.log('stdout: ' + data);
+});
+
+ls.stderr.on('data', function (data) {
+  console.log('stderr: ' + data);
+});
+
+ls.on('close', function (code) {
+  console.log('child process exited with code ' + code);
+});
+ +

Utilisation child_process dans les extensions non-jpm

+ +

 

+ +
// Import SDK Stuff
+const COMMONJS_URI = 'resource://gre/modules/commonjs';
+const { require } = Cu.import(COMMONJS_URI + '/toolkit/require.js', {});
+var child_process = require('sdk/system/child_process');
+
+// Use it in the same way as in the example above
+ +

 

diff --git a/files/fr/mozilla/add-ons/sdk/low-level_apis/ui_button_action/index.html b/files/fr/mozilla/add-ons/sdk/low-level_apis/ui_button_action/index.html new file mode 100644 index 0000000000..f018689432 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/low-level_apis/ui_button_action/index.html @@ -0,0 +1,659 @@ +--- +title: ui/button/action +slug: Mozilla/Add-ons/SDK/Low-Level_APIs/ui_button_action +translation_of: Archive/Add-ons/Add-on_SDK/Low-Level_APIs/ui_button_action +--- +

{{AddonSidebar}}

+ +
Experimental
+ +

Ajouter un boutton dans l'interface utilisateur de Firefox. Avec ce module vous pourrez créer des bouttons contenant des icônes et répondant aux clic de la sourie.

+ +

Usage

+ +


+ Créer des  bouttons

+ +

Pour créer un boutton, vous devez lui donné un identifiant (id), une icône et un libellé:

+ +
var { ActionButton } = require("sdk/ui/button/action");
+
+var button = ActionButton({
+    id: "my-button",
+    label: "my button",
+    icon: {
+      "16": "./firefox-16.png",
+      "32": "./firefox-32.png"
+    },
+    onClick: function(state) {
+        console.log("button '" + state.label + "' was clicked");
+    }
+  });
+ +

By default, the button appears in the Firefox toolbar:

+ +

However, users can move it to the Firefox menu panel using the toolbar customization feature:

+ +

+ +

Badged buttons

+ +
+

New in Firefox 36.

+
+ +

You can add a "badge" to a button using its badge property. This can be a number or a string, and you can update it at any time. By default the badge's color is red, but you can set your own color using the badgeColor property, specified as a CSS <color> value:

+ +
var { ToggleButton } = require("sdk/ui/button/toggle");
+
+var button = ToggleButton({
+    id: "my-button1",
+    label: "my button1",
+    icon: "./icon-16.png",
+    onChange: changed,
+    badge: 0,
+    badgeColor: "#00AAAA"
+  });
+
+function changed(state) {
+  button.badge = state.badge + 1;
+  if (state.checked) {
+    button.badgeColor = "#AA00AA";
+  }
+  else {
+    button.badgeColor = "#00AAAA";
+  }
+}
+ +

+ +

Specifying multiple icons

+ +

You can specify just one icon, or multiple icons in different sizes.

+ +

If you specify multiple icons, Firefox will select the best-fitting icon based on the device screen resolution and the place the icon appears. For example, in the screenshots above, Firefox uses the small icon when the button is in the toolbar and the large icon when the button is in the menu panel. Read more about specifying icons in the reference documentation for the ActionButton constructor.

+ +

Responding to click events

+ +

You can respond to click events by assigning a listener to the button's click event. You can do this in the button's constructor, by assigning the listener to the onClick option. You can also add, or change, the listener afterwards:

+ +
var { ActionButton } = require("sdk/ui/button/action");
+
+var button = ActionButton({
+    id: "my-button",
+    label: "my button",
+    icon: {
+      "16": "./firefox-16.png",
+      "32": "./firefox-32.png"
+    },
+    onClick: firstClick
+  });
+
+function firstClick(state) {
+  console.log("You clicked '" + state.label + "'");
+  button.removeListener("click", firstClick);
+  button.on("click", subsequentClicks);
+}
+
+function subsequentClicks(state) {
+  console.log("You clicked '" +  state.label + "' again");
+}
+ +

The listener is passed a state object that contains all the button's properties.

+ +

You can generate click events programmatically with the button's click() method.

+ +

Disabling buttons

+ +

You can disable a button by setting its disabled property to true. A disabled button will not generate click events and its icon will appear disabled:

+ +

+ +

Updating state

+ +

You can update all the button's properties except for its id.

+ +

By default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates the button's state across all open windows and tabs.

+ +

You can set state to be specific to a window or tab using the button's state() method. To set state like this, call state() with 2 parameters:

+ + + +

Here's an add-on with a button that disables itself when you click it, but only for the currently active window:

+ +
var { ActionButton } = require("sdk/ui/button/action");
+
+var button = ActionButton({
+    id: "my-button",
+    label: "my button",
+    icon: {
+      "16": "./firefox-16.png",
+      "32": "./firefox-32.png"
+    },
+    onClick: disableForThisWindow
+  });
+
+function disableForThisWindow(state) {
+  button.state("window", {
+    disabled: true
+  });
+}
+ +

To fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state:

+ +
var labelForActiveTab = button.state("tab").label;
+ +

To learn more about this, see the API documentation for state().

+ +

Destroying buttons

+ +

When you've finished with a button, destroy it by calling its destroy() method. After that, any attempts to access any of its properties or to call any of its methods will throw exceptions.

+ +

Globals

+ +

Constructors

+ +

ActionButton(options)

+ +

Creates an action button.

+ +
Parameters
+ +

options : object
+ Required options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
idstring +

The button's ID. This is used internally to keep track of this button. The ID must be unique within your add-on.

+
labelstring +

The button's human-readable label. When the button is in the toolbar, this appears in a tooltip, and when the button is in the menu, it appears underneath the button as a legend.

+
iconurl, string, object +

One or more icons for the button. You can specify this in one of three ways: 

+ +
    +
  • as a resource:// URL pointing at an icon file in your add-on's "data" directory, typically constructed using self.data.url(iconfile)
  • +
  • as a relative path: a string in the form "./iconfile", where "iconfile" is a relative path to the icon file beginning in your add-on's "data" directory
  • +
  • as an object, or dictionary of key-value pairs. Here you can specify a range of sizes for your button's icon. Each key-value pair specifies an icon: +
      +
    • each value specifies an image file as a resource:// URL or relative path.
    • +
    • each key must be a numeric string such as "16", or "32", which represents the size in pixels of the corresponding image.
    • +
    +
  • +
+ +
+var { ActionButton } = require('sdk/ui/button/action');
+var self = require("sdk/self");
+
+var button1 = ActionButton({
+    id: "my-button1",
+    label: "my button1",
+    icon: self.data.url("firefox-16.png")
+  });
+
+var button2 = ActionButton({
+    id: "my-button2",
+    label: "my button2",
+    icon: "./firefox-16.png"
+  });
+
+var button3 = ActionButton({
+    id: "my-button3",
+    label: "my button3",
+    icon: {
+      "16" : "./firefox-16.png",
+      "32" : "./firefox-32.png",
+      "64" : "./firefox-64.png"
+    }
+  });
+ +

If you use the final form, Firefox will automatically choose the best-fit icon for your button, depending on the device screen resolution and where the button is in the UI. On a device with a "normal" screen resolution, the toolbar has space for 18 x 18 pixels and the menu panel has space for 32 x 32 pixels. On a high resolution screen (such as a HiDPI display), these are doubled to 36 x 36 and 64 x 64 pixels, respectively. So you can supply three icon files:

+ +
+icon: {
+  "16": "./addon16.png",
+  "32": "./addon32.png",
+  "64": "./addon64.png"
+}
+ +

This will look fine in both toolbar and menu panel, and for both screen resolutions. However, the icons in the toolbar will not quite fill the space available, so you can instead supply four icons:

+ +
+icon: {
+  "18": "./addon18.png", // toolbar icon non HiDPI
+  "32": "./addon32.png", // menu panel icon non HiDPI
+  "36": "./addon36.png", // toolbar icon HiDPI
+  "64": "./addon64.png"  // menu panel icon HiDPI
+}
+
+
+ +

Optional options:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType 
disabledboolean +

Determines whether the button is disabled. Disabled buttons appear disabled in the UI, and do not respond to clicks. Defaults to false.

+
onClickfunction +

Click handler for the button.

+
badgeNumber or String +
+

New in Firefox 36.

+
+ +

Badge to attach to the button.

+ +

The badge can contain as many characters (or digits) as you like, but only the first four will be displayed.

+
badgeColorCSS <color> value +
+

New in Firefox 36.

+
+ +

Color for the badge. If badgeColor is omitted and badge is specified, then the badge is red.

+
+ +

ActionButton

+ +

Methods

+ +

click()

+ +

Click the button. This will cause the button to generate the click event:

+ +
var { ActionButton } = require('sdk/ui/button/action');
+
+var button = ActionButton({
+  id: "my-button",
+  label: "my button",
+  icon: {
+    "16": "./firefox-16.png",
+    "32": "./firefox-32.png"
+  },
+  onClick: function(state) {
+      console.log("You clicked '" + state.label + "'");
+  }
+});
+
+button.click();
+
+ +

state()

+ +

Get or set the button's state for a specific window or tab.

+ +

By default, a button's properties are global, meaning that they are the same across all open windows and tabs, and that if you update these properties, then they are updated across all windows and tabs. But sometimes you want a button attached to one window (or tab) to have a different state to a button attached to a different window (or tab). That's what state() is for.

+ +

To set a button's properties for a specific window or tab, call state(), passing it the window or tab you want the property to apply to, and the property value to set. A special shortcut allows you to pass the string "window" or "tab" to select the currently active window or tab.

+ +

For example, if you have a button like this:

+ +
var { ActionButton } = require('sdk/ui/button/action');
+
+var button = ActionButton({
+  id: "my-button",
+  label: "default",
+  icon: "./firefox-16.png"
+});
+ +

You can change its label for only the currently active window like this:

+ +
button.state("window", {
+  "label" : "window-specific label"
+});
+ +

You can change its label for only the currently active tab like this:

+ +
button.state("tab", {
+  "label" : "tab-specific label"
+});
+
+ +

To fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will return a state object containing all the properties for the button associated with that window or tab. Again. you can use the strings "window" or "tab" as shortcuts. For example, this add-on:

+ + + +
var { ActionButton } = require('sdk/ui/button/action');
+var tabs = require("sdk/tabs");
+
+var button = ActionButton({
+  id: "my-button",
+  label: "default label",
+  icon: "./firefox-16.png"
+});
+
+tabs.open({
+  url: "https://mozilla.org/",
+  onOpen: onNewTab
+});
+
+function onNewTab(tab) {
+  // Modify the label only for the new tab
+  button.state(tab, {
+    "label" : "tab-specific label"
+  });
+
+  // access the global label -> "default label"
+  console.log(button.label);
+
+  // access the window's label -> "default label"
+  console.log(button.state("window").label);
+
+  // access the first tab's label -> "default label"
+  console.log(button.state(tabs[0]).label);
+
+  // access the second tab's label -> "tab-specific label"
+  console.log(button.state(tabs[1]).label);
+}
+ +

Setting a property won't affect a more-specific property setting. For example, if you have a window with two tabs, and you set a tab-specific label, then set the window-specific label, this will not overwrite the tab-specific label:

+ +
var { ActionButton } = require('sdk/ui/button/action');
+var tabs = require("sdk/tabs");
+
+var button = ActionButton({
+  id: "my-button",
+  label: "default label",
+  icon: "./firefox-16.png"
+});
+
+tabs.open({
+  url: "https://mozilla.org/",
+  onOpen: onNewTab
+});
+
+function onNewTab(tab) {
+  // Modify the label only for the new tab
+  button.state(tab, {
+    "label" : "tab-specific label"
+  });
+
+  // Modify the label for the window
+  button.state("window", {
+    "label" : "window-specific label"
+  });
+
+  // access the global label -> "default label"
+  console.log(button.label);
+
+  // access the window's label -> "window-specific label"
+  console.log(button.state("window").label);
+
+  // access the first tab's label -> "window-specific label"
+  console.log(button.state(tabs[0]).label);
+
+  // access the second tab's label -> "tab-specific label"
+  console.log(button.state(tabs[1]).label);
+}
+ +

The best way to think of this is as a tree: the global state is the root, followed by the state for each window, followed by the state for each tab in a window. If a property value for a node in the tree has not been set explicitly using state(), then it inherits its value from the next level up. So if you have one window containing two tabs, and have set the button's label only for tab A, then tab B will inherit label's value from the window, and changing the value for the window will implicitly change the value for tab B.

+ +

To delete a tab- or window-specific state, assign null to the property. After that, the property will inherit its value from the less-specific state as before:

+ +
var { ActionButton } = require('sdk/ui/button/action');
+var tabs = require("sdk/tabs");
+
+var button = ActionButton({
+  id: "my-button",
+  label: "default label",
+  icon: "./firefox-16.png"
+});
+
+tabs.open({
+  url: "https://mozilla.org/",
+  onOpen: onNewTab
+});
+
+function onNewTab(tab) {
+  // Modify the label only for the new tab
+  button.state(tab, {
+    "label" : "tab-specific label"
+  });
+
+  // Modify the label for the window
+  button.state("window", {
+    "label" : "window-specific label"
+  });
+
+  // access the global label -> "default label"
+  console.log(button.label);
+
+  // access the window's label -> "window-specific label"
+  console.log(button.state("window").label);
+
+  // access the first tab's label -> "window-specific label"
+  console.log(button.state(tabs[0]).label);
+
+  // access the second tab's label -> "tab-specific label"
+  console.log(button.state(tabs[1]).label);
+
+  // Reset the tab-specific state
+  button.state(tab, null);
+
+  // access the second tab's label -> "window-specific label"
+  console.log(button.state(tabs[1]).label);
+}
+ +

Finally, you can pass the button itself into state(). This is an alternative way to set or get the global state. The reason for using this, rather than setting properties individually, is that you can define an object with the properties to set in one place, then apply it to the global state with a single line:

+ +
const defaultState = {
+  "label": "default label",
+  "icon": "./default.png",
+}
+
+const differentState = {
+  "label": "different label",
+  "icon": "./different.png",
+}
+
+var { ActionButton } = require("sdk/ui/button/action");
+
+var button = ActionButton({
+    id: "default-label",
+    label: "default label",
+    icon: "./default.png",
+    onClick: function(state) {
+      if (button.label == "default label") {
+        button.state(button, differentState);
+      }
+      else {
+        button.state(button, defaultState);
+      }
+      console.log(button.state(button).label);
+      console.log(button.state(button).icon);
+    }
+  });
+
+ +
Parameters
+ +

target : button, tab, window, string

+ + + +

state : object, null
+ Include this parameter only if you are setting state. It is an object containing all the properties you wish to set. For example:

+ +
button.state("tab", {
+  "label" : "tab-specific label",
+  "icon": "./tab-specific-icon.ico"
+});
+ +

To reset state, pass null:

+ +
button.state("tab", null);
+ +
Returns
+ +

state : if you have passed the second state argument to make this function a setter, it returns undefined. Otherwise, it functions as a getter and returns the button's state for the specified object. This logs the state for the button associated with the currently active tab:

+ +
console.log(button.state("tab"));
+ +

This object represents a snapshot of the state at the time state() is called. It is not kept up to date with changes made to the button:

+ +
button.label = "foo";
+var state = button.state(button);
+button.label = "bar";
+console.log(state.label) // foo
+ +

on()

+ +

Add a listener to an event emitted by the button. The button only emits one type of event, click:

+ +
button.on("click", handleClick)
+
+function handleClick(state) {
+  console.log("button '" + state.label + "' was clicked");
+}
+ +
Parameters
+ +

event : string
+ The event to listen for. Action buttons only emit one type of event, "click".

+ +

listener : function
+ Function that will be called on click.

+ +

once()

+ +

Assign a listener to the first occurrence only of an event emitted by the button. The button only emits one type of event, click. The listener is automatically removed after the first time the event is emitted.

+ +
Parameters
+ +

event : string
+ The event to listen for. Action buttons only emit one type of event, "click".

+ +

listener : function
+ Function that will be called on click.

+ +

removeListener()

+ +

Removes an event listener. For example, this code is equivalent to once():

+ +
button.on("click", handleClick)
+
+function handleClick(state) {
+  console.log("button '" + state.label + "' was clicked");
+  button.removeListener("click", handleClick);
+} 
+ +
Parameters
+ +

event : string
+ The event to listener is listening for. Action buttons only emit one type of event, "click".

+ +

listener : function
+ The listener to remove.

+ +

destroy()

+ +

Destroy the button. After calling this function, the button will no longer appear in the UI, and accessing any of its properties or methods will throw an error.

+ +

Properties

+ +

id

+ +

The button's unique ID. This is read-only.

+ +

label

+ +

The button's label.

+ +

icon

+ +

The button's icon or icons, as a URL, relative path, or object containing a set of key-value pairs.

+ +

disabled

+ +

Boolean property indicating whether or not the button is disabled.

+ +

badge

+ +
+

New in Firefox 36.

+
+ +

Value to attach to the button as a badge. May be a number or a string.

+ +

The badge can contain as many characters (or digits) as you like, but only the first four will be displayed.

+ +

badgeColor

+ +
+

New in Firefox 36.

+
+ +

Color for the badge, specified as a CSS <color> value.

+ +

Events

+ +

click

+ +

This event is emitted when a user clicks the button or your add-on calls the button's click() method.

+ +
Arguments
+ +

state : The button's state. This contains all the button's properties.

diff --git a/files/fr/mozilla/add-ons/sdk/tools/cfx_to_jpm/index.html b/files/fr/mozilla/add-ons/sdk/tools/cfx_to_jpm/index.html new file mode 100644 index 0000000000..e8b50f5006 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tools/cfx_to_jpm/index.html @@ -0,0 +1,192 @@ +--- +title: De cfx à jpm +slug: Mozilla/Add-ons/SDK/Tools/cfx_to_jpm +translation_of: Archive/Add-ons/Add-on_SDK/Tools/cfx_to_jpm +--- +
+

L'Add-on SDK inclut un outil de ligne de commande que vous utilisez pour initialiser, exécuter, tester, et empaqueter des add-ons. L'outil actuel est appelé jpm, il est basé sur Node.js . Il remplace l'outil cfx.

+ +

Vous pouvez utiliser jpm à partir de Firefox 38.

+ +

Cet article met en évidence les principales différences entre cfx et jpm.

+
+ +

Un guide pour travailler avec jpm si vous êtes déjà familier avec cfx.

+ +

Installation

+ +

cfx est basée sur Python et est distribué comme un fichier zip. jpm est baser sur Node.js qui est distribué par npm . Donc, pour jpm vous n'avez pas besoin de Python, mais vous avez besoin npm.

+ +

Pour obtenir les mises de cfx vous deviez télécharger et extraire un fichier zip, tandis que pour obtenir la nouvelle version de jpm, utilisez npm update .

+ +

Pour obtenir des instructions d'installation de jmp, consultez la section de l' Installation dans la référentiel de jmp.

+ +

Activation

+ +

Vous devez appeler cfx activate avant de pouvoir utiliser cfx, et cela ne fonctionne que dans le shell de commande de courant:. Si vous ouvrez un nouveau shell, vous devez appeler activate de nouveau

+ +

Avec jpm, pas d'activation. Une fois qu'il est installé, vous pouvez simplement l'utiliser.

+ +

Incompatibilités

+ +

Dans la plupart cas, les add-ons créés avec cfx fonctionnent bien avec jpm. Cependant, il y a quelques différences que vous devez connaitre.

+ +

Add-on ID

+ +

L'ID de add-on est l'identifiant unique de votre add-on. Dans un xpi, c'est le champ ID dans le fichier Manifest d'instalation de l'add-on (install.rdf).

+ +

L'identifiant est utilisé à des fins variées. Par exemple: addons.mozilla.org l'utilise pour distinguer entre les nouvelles add-ons et les mises à jour d'add-ons existantes, et le module simple-storage l'utilise pour déterminer lesquelles des données stockées appartiennent à tel add-on.

+ +

Manipulation avec l'ID cfx

+ +

Lorsque vous utilisez cfx, l'ID est tiré du champ id dans le fichier de package.json de l'add-on. Vous pouvez éditer ce fichier pour créer votre propre identité, mais si vous ne le faites pas, cfx va le générer pour vous, ce qui va ressembler à quelque chose comme "jid1-F3BoogbjQJE67A". L'ID Add-on doit être l'un des deux types suivant : un GUID ou une chaîne qui comprend un symbole "@". Le SDK ne prévoit que le dernier format, et si l'ID dans package.json ne contient pas de "@", cfx xpi ajouter "@jetpack" dans le champ de package.json, ce qui transforme l'ID de l'add-on.

+ +

Donc: si vous n'avez jamais manipulé l'ID lors de l'utilisation cfx, alors la valeur dans le package.json de votre add-on sera quelque chose comme "jid1-F3BoogbjQJE67A", et l'ID correspondant dans la install.rdf sera "jid1-F3BoogbjQJE67A@jetpack".

+ +

Manipulation d'ID avec jpm

+ +

Lorsque vous créez un xpi avec jpm xpi:

+ + + +

Ce que vous devez faire

+ +

Tout cela signifie que: si votre package.json contient un champ id, et sa valeur ne contient pas «@», alors vous devez ajouter "@jetpack» lors du passage à jpm .

+ +

Si vous faites cela, l'ID de l'add-on sera la même que l'id utilisée avec cfx.

+ +

Point d'entrée

+ +

Le point d'entrée de l'add-on est le fichier qui est exécutée lorsque l'add-on a besoin de s'initialiser: par exemple, au démarrage de Firefox, ou lorsque l'add-on est installé, activé, ou mis à niveau. Avec cfx, la valeur par défaut à "lib/main.js", même si elle peut être réglée sur un autre fichier en utilisant le main champ dans le package.json .

+ +

Dans jpm, le point d'entrée par défaut est "index.js". Donc, lors de la commutation vers jpm:

+ + + +

Chargement des modules

+ +

L'outil jpm utilise la même logique que Node.js pour déterminer comment résoudre l'argument require(). Dans la plupart des cas, c'est la même logique que cfx. Cependant, il existe quelques différences, parce certaines compatibilités ont été retirées.

+ +

Requérir à des modules locaux

+ +

Supposons que votre add-on est structuré en modules séparés :

+ + + +

Lorsque vous voulez utiliser un module "utils.js" dans "main.js", vous devez utiliser un chemin relatif à "main.js", et le préfixer avec "./" pour indiquer que c'est un chemin relatif:

+ +
var utils = require("./utils");
+ +

Cependant, avec cfx vous êtes également autorisé à omettre le "./":

+ +
var utils = require("utils"); // this will not work with jpm!
+ +

Cette seconde forme ne fonctionnera pas avec jpm.

+ +

Requérir des modules de code de test

+ +

Similarly, suppose you've written some tests for your add-on:

+ + + +

Avec cfx, le code de "test-my-addon.js" peut importer "my-addon.js" en utilisant une déclaration de ce genre:

+ +
var my_addon = require("my-addon"); // ceci ne fonctionne pas avec jpm!
+ +

Avec jpm, vous devez spécifier le chemin vers «my-addon" explicitement, en utilisant un chemin relatif:

+ +
var my_addon = require("../lib/my-addon");
+
+ +

Modules tiers

+ +

Le SDK a toujours soutenu les modules tiers: les développeurs peuvent écrire leurs propres modules qui étendent les API du SDK ou ajouter de nouvelles API, et d'autres add-on peuvent faire usage de ces modules de la même manière qu'ils utilisent les modules intégré au SDK.

+ +

Dans jpm cette façon d'utiliser des modules tiers ne fonctionne plus. Au lieu de cela, jpm n'accepte que les modules tiers hébergés sur la npm, vous pouvez les utiliser en les installant à partir de la npm dans l'arbre de répertoire de votre add-on. Voir le tutoriel utilisant des modules tiers avec jpm.

+ +

Les commandes et les options de commande

+ +

Commandes définitivement retiré

+ +

jpm ne soutient plus les commandes cfx "interne".

+ +

Options définitivement retiré

+ +

jpm ne soutient plus :

+ +
--extra-packages
+--use-config
+--package-path
+--pkgdir
+--no-strip-xpi
+--harness-option
+--manifest-overload
+--output-file
+--templatedir
+--keydir
+--profiledir
+--overload-modules
+--static-args
+--app
+--no-run
+--addons
+--e10s
+--logfile
+--dependencies
+--test-runner-pkg
+ +

Au lieu de --profiledir et de --overload-modules, utilisez --profile et --overload

+ +

Champs Package.json

+ +

Beaucoup de champs package.json sont des commandes implicites de cfx. Dans jpm, nous avons supprimé le soutien de certains de ces domaines, et travaillons toujours sur le soutien des autres.

+ +

Champs définitivement retiré

+ + + +

Echappement dans Package.json

+ +

Où avec cfx vous auriez dû échapper avec 2 voir 3 barres obliques inverses (\), jpm n'en a besoin que d'une.

+ +

 

diff --git a/files/fr/mozilla/add-ons/sdk/tools/index.html b/files/fr/mozilla/add-ons/sdk/tools/index.html new file mode 100644 index 0000000000..89f1db963b --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tools/index.html @@ -0,0 +1,13 @@ +--- +title: Tools +slug: Mozilla/Add-ons/SDK/Tools +tags: + - Add-on SDK + - CFX + - JPM + - TopicStub +translation_of: Archive/Add-ons/Add-on_SDK/Tools +--- +

Les articles répertoriés ici fournissent une référence pour les outils du SDK:

+ +

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

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

Vous pouvez utiliser jpm pour Firefox 38 et au-delà.

+ +

Cet article est la référence pour jpm.

+
+ +

The Node-based replacement for cfx. Enables you to test, run, and package add-ons.

+ +

Voir aussi le tutoriel jpm pour débuter.

+ +

jpm usage is:

+ +
jpm [command] [options]
+
+ +

jpm supports the following global options:

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

Installation

+ +

jpm is distributed using the node package manager npm, so to get jpm you need to have npm installed, if you haven't already. npm is included in Node.js. To install npm, you can either visit nodejs.org and download the latest binary or if you have a package manager like APT installed on your system, you might want to use this package manager to install npm. For example, if you are using an Ubuntu or Debian operating system, execute sudo apt-get install nodejs followed by sudo apt-get install npm in a terminal window.

+ +

After that you can install jpm just as you would any other npm package:

+ +
npm install jpm --global
+ +

Depending on your setup, you might need to run this as an administrator:

+ +
sudo npm install jpm --global
+ +

Or, you can install jpm using git:

+ +
git clone https://github.com/mozilla-jetpack/jpm.git
+cd jpm
+npm install
+npm link
+
+ +

À l'invite de commande, tapez:

+ +
jpm
+ +

You should see a screen summarizing the available jpm commands. Note that unlike cfx, jpm is available in every command prompt you start, as long as you installed it with the --global flag.

+ +

If you get an error message saying  /usr/bin/env: node: No such file or directory and you have installed nodejs through a package manager, nodejs may have been installed in the wrong directory. A corresponding topic at stackoverflow.org might help you to solve this problem. Basically, you can solve it by creating a symlink to the node:

+ +
sudo ln -s "$(which nodejs)" /usr/bin/node
+ +

Problems?

+ +

If you don't see this, ask for help. SDK users and project team members discuss problems and proposals on the project mailing list. Someone else may have had the same problem you do, so try searching the list. You're welcome to post a question, too. You can also chat with other SDK users in #jetpack on Mozilla's IRC network.

+ +

Command reference

+ +

There are six jpm commands:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
jpm initCreate a skeleton add-on as a starting point for your own add-on.
jpm runLaunch an instance of Firefox with your add-on installed.
jpm testRuns your add-on's unit tests.
jpm xpiPackage your add-on as an XPI file, which is the install file format for Firefox add-ons.
jpm postPackage your add-on as an XPI file, then post it to some url.
jpm watchpostPackage your add-on as an XPI file whenever there is a file changed, and post that to some url.
jpm signPackage your add-on as an XPI file, then retrieve a new XPI signed by Mozilla.
+ +

jpm init

+ +

This command initializes a new add-on from scratch.

+ +

Create a new directory, change into it, and run jpm init.

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

You'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file.

+ + + +

Most of these fields have a default, which is shown in brackets after the question. If you just press Enter, your add-on will get the default value.

+ +

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.

+ +

Then jpm will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure:

+ + + +

jpm run

+ +

This command runs a new instance of Firefox with the add-on installed:

+ +
jpm run
+ +

jpm run accepts the following options:

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

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

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

Pass extra arguments to Firefox.

+ +

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

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

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

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

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

+ +

See Overloading the built-in modules for more information.

+
-p --profile= PROFILE +

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

+ +

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

+ +

See Using profiles for more information.

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

jpm test

+ +

Use this command to run an add-on's unit tests. It will:

+ + + +
jpm test
+
+ +

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

+ +

jpm test accepts the following options:

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

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

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

See Selecting a browser version.

+
--binary-args CMDARGS +

Pass extra arguments to Firefox.

+ +

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

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

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

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

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

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

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

+
-o --overload PATH +

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

+ +

See Overloading the built-in modules for more information.

+
-p --profile PROFILE +

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

+ +

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

+ +

See Using profiles for more information.

+
--stop-on-error +

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

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

Run tests NUMBER of times:

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

jpm xpi

+ +

This command packages the add-on as an XPI file, which is the install file format for Mozilla add-ons.

+ +
jpm xpi
+ +

It looks for a file called package.json in the current directory and creates the corresponding XPI file. It ignores any ZIPs or XPIs in the add-on's root, and any test files. It includes all other files. If you want to exclude extra files, see the .jpmignore file.

+ +

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

+ +

jpm xpi accepts the following option:

+ + + + + + + + +
-v --verbose +

Verbose operation:

+ +
+jpm xpi -v
+
+ +

jpm post

+ +

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

+ +
jpm post
+ +

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

+ +

jpm post accepts the following options:

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

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

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

See Using Post and Watchpost for more information.

+
-v --verbose +

Verbose operation:

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

jpm watchpost

+ +

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

+ +
jpm watchpost
+ +

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

+ +

jpm watchpost accepts the following options:

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

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

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

See Using Post and Watchpost for more information.

+
-v --verbose +

Verbose operation:

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

jpm sign

+ +
+

This feature is only supported from jpm 1.0.4 onwards.

+
+ +

This command retrieves a new XPI for your add-on signed by Mozilla. This allows you to self-host your add-on so that users can install it without error when signed add-ons are required.

+ +
jpm sign --api-key ${AMO_API_KEY} --api-secret ${AMO_API_SECRET}
+ +

This creates an XPI, submits it to the addons.mozilla.org signing API, then downloads a new signed XPI to the working directory if it passes validation. Here are some possible outcomes of running the sign command:

+ + + +

Under the hood, jpm sign creates an unlisted add-on inside addons.mozilla.org which means you must distribute the XPI file yourself in order for your users to install it. If you need to create a listed add-on, just submit it directly to addons.mozilla.org where it will be signed automatically. See the debugging section if you're experiencing difficulty installing a signed add-on.

+ +

jpm sign accepts the following options:

+ + + + + + + + + + + + + + + + +
--api-key API_KEY +

API access key (string) generated on the addons.mozilla.org key management page.

+
--api-secret API_SECRET +

API access secret (string) generated on the addons.mozilla.org key management page. This value should be guarded with care and never checked into version control. If your secret is compromised, another developer could upload add-ons to your account. You should revoke and regenerate compromised API credentials immediately.

+
--api-url-prefix http://.../api +

An optional API URL prefix in case you'd like to use a pre-production signing API. Here is an example of using a dev instance of addons.mozilla.org :

+ +
+jpm sign ... --api-url-prefix https://addons-dev.allizom.org/api/v3
+
+ +

Techniques

+ +

Selecting a browser version

+ +

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

+ + + +

Using .jpmignore to ignore files

+ +

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

+ +

Here is an example:

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

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

+ +

Using profiles

+ +

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

+ +

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

+ +

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

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

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

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

Developing without browser restarts

+ +

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

+ + + +

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

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

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

+ +

Overloading the built-in modules

+ +

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

+ +

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

+ + + +
jpm run -o
+
+ +

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

+ +
jpm run -o "/path/to/SDK/"
+ +

Supporting updates for self-hosted add-ons

+ +
+

This feature is only supported from jpm 1.0.3 onwards.

+
+ +

When you make updates to your add-on to add features or fix bugs, you'll want any previously installed versions of the add-on to update themselves to the new version.

+ +

If you list your add-on on addons.mozilla.org, then all you have to do here is submit the new version; add-ons default to checking addons.mozilla.org for new versions of themselves. You can stop reading this section.

+ +

If you do not list your add-on on addons.mozilla.org, you need to generate a Mozilla-signed XPI and tell Firefox where it can find new versions of your add-on. The way this works is:

+ + + +

To do this, include two extra keys in package.json:

+ + + +

+ +

If you include updateURL and updateLink (and also updateKey in case updateURL is not HTTPS), then jpm xpi will:

+ + + +

You then host the update manifest at updateURL, and host new versions of the XPI at updateLink.

+ +

For some more details on this, see Automatic Add-on Update Checking.

diff --git a/files/fr/mozilla/add-ons/sdk/tutorials/add_a_context_menu_item/index.html b/files/fr/mozilla/add-ons/sdk/tutorials/add_a_context_menu_item/index.html new file mode 100644 index 0000000000..1ad8700c3d --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tutorials/add_a_context_menu_item/index.html @@ -0,0 +1,115 @@ +--- +title: Add a Context Menu Item +slug: Mozilla/Add-ons/SDK/Tutorials/Add_a_Context_Menu_Item +translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Add_a_Context_Menu_Item +--- +

{{AddonSidebar}}

+ +
+

Pour suivre ce tuto , vous aurez besoin d'avoir appris des rudiments de jpm.

+
+ +

Pour ajouter des éléments et des sous-menus dans le menu contextuel de Firefox, utilisez le module context-menu.

+ +

Voici un add-on qui ajoute un nouvel élément de menu contextuel. L'élément est affiché à chaque fois qu'une séléction est opérée dans la page. Si l'élément est cliqué, la séléction est envoyé au code principal.

+ +
var contextMenu = require("sdk/context-menu");
+var menuItem = contextMenu.Item({
+  label: "Log Selection",
+  context: contextMenu.SelectionContext(),
+  contentScript: 'self.on("click", function () {' +
+                 '  var text = window.getSelection().toString();' +
+                 '  self.postMessage(text);' +
+                 '});',
+  onMessage: function (selectionText) {
+    console.log(selectionText);
+  }
+});
+ +

Executer l'add-on, charger une page web, séléctioner un texte et faites un clic droit, le nouvel élément doit apparaitre:

+ +

Click it, and the selection is logged to the console (or the shell, if you're running an instance of Firefox from the command line):

+ +
info: elephantine lizard
+
+ +

Details

+ +

All this add-on does is to construct a context menu item. You don't need to add it: once you have constructed the item, it is automatically added in the correct context. The constructor in this case takes four options: label, context, contentScript, and onMessage.

+ +

label

+ +

The label is just the string that's displayed.

+ +

context

+ +

The context describes the circumstances in which the item should be shown. The context-menu module provides a number of simple built-in contexts, including this SelectionContext(), which means: display the item when something on the page is selected.

+ +

If these simple contexts aren't enough, you can define more sophisticated contexts using scripts.

+ +

contentScript

+ +

This attaches a script to the item. In this case the script listens for the user to click on the item, then sends a message to the add-on containing the selected text.

+ +

onMessage

+ +

The onMessage property provides a way for the add-on code to respond to messages from the script attached to the context menu item. In this case it just logs the selected text.

+ +

So:

+ +
    +
  1. the user clicks the item
  2. +
  3. the content script's click event fires, and the content script retrieves the selected text and sends a message to the add-on
  4. +
  5. the add-on's message event fires, and the add-on code's handler function is passed the selected text, which it logs
  6. +
+ +

More options

+ +

Adding an image

+ +

You can add an image to a context menu item with the image option. This is a URL pointing to a 16x16 icon that's displayed at the left side of the context menu item. Typically you'd store the image in your add-on's "data" directory, and construct the URL using self.data.url():

+ +
var self = require("sdk/self");
+
+var contextMenu = require("sdk/context-menu");
+var menuItem = contextMenu.Item({
+  label: "Log Selection",
+  context: contextMenu.SelectionContext(),
+  contentScript: 'self.on("click", function () {' +
+                 '  var text = window.getSelection().toString();' +
+                 '  self.postMessage(text);' +
+                 '});',
+  image: self.data.url("icon-16.png"),
+  onMessage: function (selectionText) {
+    console.log(selectionText);
+  }
+});
+ +

Adding an access key

+ +
+

New in Firefox 35.

+
+ +

From Firefox 35 you can specify an access key using the accessKey option. This must be a single-character string. Pressing the key selects the option when the context menu is open:

+ +
var contextMenu = require("sdk/context-menu");
+var menuItem = contextMenu.Item({
+  label: "Log Selection",
+  context: contextMenu.SelectionContext(),
+  contentScript: 'self.on("click", function () {' +
+                 '  var text = window.getSelection().toString();' +
+                 '  self.postMessage(text);' +
+                 '});',
+  accessKey: "l",
+  onMessage: function (selectionText) {
+    console.log(selectionText);
+  }
+});
+
+ +

 

+ +

Learning More

+ +

To learn more about the context-menu module, see the context-menu API reference.

diff --git a/files/fr/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html b/files/fr/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html new file mode 100644 index 0000000000..09fa1442a9 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tutorials/getting_started_(jpm)/index.html @@ -0,0 +1,165 @@ +--- +title: Commencer avec jpm +slug: Mozilla/Add-ons/SDK/Tutorials/Getting_Started_(jpm) +translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/Getting_Started_(jpm) +--- +
+

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

+ +

You can use jpm from Firefox 38 onwards.

+ +

This article describes how to develop using jpm.

+
+ +

Ce tutoriel est un exemple de création d'une add-on en utilisant le SDK.

+ +

Prérequis

+ +

Pour créer des add-ons pour Firefox en utilisant le SDK, vous aurez besoin:

+ + + +

Initialisation d'un add-on vide

+ +

Dans l'invite de commande, créez un nouveau répertoire. Accédez à, tapez jpm init, et appuyez sur Entrée:

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

Vous serez alors invité à fournir quelques informations sur votre add-on: elles seront utilisées pour créer votre fichier package.json. Pour l'instant, appuyez sur Entrée pour accepter la valeur par défaut pour chaque propriété. Pour plus d'informations sur jpm init, voir le commande de référence jpm .

+ +

Une fois que vous avez fourni une valeur ou accepté la valeur par défaut pour ces propriétés, vous verrez le contenu complet de "package.json" que vous validerez.

+ +

Mise en œuvre de l'add-on

+ +

Maintenant, vous pouvez écrire le code de l'add-on. Sauf si vous avez changé la valeur du "point d'entrée"("main"dans package.json), allez dans le fichier "index.js" à la racine de votre add-on. Ce fichier a été créé dans l'étape précédente. Ouvrez-le et ajoutez le code suivant:

+ +
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/");
+}
+
+ +
+

Notez que par défaut le "point d'entrée" dans jpm est "index.js", ce qui signifie que votre fichier principal est "index.js", et il se trouve à la racine de votre add-on.

+ +

Dans cfx, le "point d'entrée" par défaut est "main.js», il se trouve dans le répertoire "lib" sous la racine de l'add-on.

+
+ +

Enregistrez le fichier.

+ +

Ensuite, créez un répertoire appelé "data" à la racine de votre add-on, et enregistrer ces trois fichiers d'icônes dans "data" :

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

Retour à l'invite de commande, tapez:

+ +
jpm run
+ +

Ceci est la commande de jpm pour lancer une nouvelle instance de Firefox avec votre add-on installée.

+ +

Si Firefox ne peut pas être localisé, vous devrez peut-être fournir le chemin d'accès (par exemple dans Ubuntu):

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

Vous pouvez egalement modifier le chemin dans le fichier \npm\node_modules\jpm\node_modules\fx-runner\lib\utils.js.

+ +

Par exemple sous windos : var rootKey = '\\Programe Files\\Mozilla Firefox\\';

+
+ +

Lorsque Firefox est lancé, dans le coin en haut à droite du navigateur, vous verrez une icône avec le logo de Firefox. Cliquez sur l'icône, et un nouvel onglet sera ouvert avec https://www.mozilla.org/ chargé.

+ +

Voilà ce que fait cette add-on. Elle utilise deux modules: le module SDK button_action, qui vous permet d'ajouter des boutons dans le navigateur, et le module tabs, qui vous permet d'effectuer des opérations de base avec des onglets. Dans ce cas, nous avons créé un bouton dont l'icône est celle de Firefox, et ajouté un gestionnaire de clic qui charge la page d'accueil de Mozilla dans un nouvel onglet.

+ +

Essayez d'éditer ce fichier. Par exemple, nous pourrions changer la page qui est chargé:

+ +
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/");
+}
+ +

À l'invite de commande, exécutez à nouveau jpm run. Vous ouvrirez cette fois en cliquant https://developer.mozilla.org/.

+ +

Empaquetté l'add-on

+ +

Lorsque vous avez terminé l'add-on et êtes prêt à la distribuer, vous aurez besoin de l'emballer dans un fichier XPI. C'est le format de fichier installable pour Firefox Add-ons. Vous pouvez distribuer xpi en les publiant sur https://addons.mozilla.org afin que les autres utilisateurs puissent la télécharger et l'installer.

+ +

Pour construire un xpi, exécutez simplement la commande jpm xpi dans le répertoire de l'add-on:

+ +
jpm xpi
+
+ +

Vous devriez voir un message du type:

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

Pour voir si cela a fonctionné, essayez d'installer le fichier xpi dans votre navigateur Firefox. Vous pouvez le faire en appuyant sur la combinaison de touches Ctrl+O (O+Cmd sur Mac) à partir de Firefox, ou en sélectionnant l'option "Ouvrir" dans le menu "Fichier" de Firefox. Cela fera apparaître une boîte de dialogue de sélection de fichier: naviguer vers le fichier "@getting-started.xpi", ouvrez-le et suivez les instructions pour installer l'add-on.

+ +

Pour distribuer votre add-on, soumettre le fichier xpi à addons.mozilla.org ou exécuter jpm sign si vous souhaitez distribuer l'add-on sur votre propre serveur.

+ +

Résumé

+ +

Dans ce tutoriel, nous avons construit et emballé une add-on en utilisant trois commandes:

+ + + +

Ce sont les trois principales commandes que vous utiliserez lors de l'élaboration d'add-ons SDK. Il y a une documentation de référence complète couvrant toutes les commandes que vous pouvez utiliser et toutes les options qu'elles prennent.

+ +

Le code de add-on lui-même utilise deux modules de SDK, action bouton et tabs. Il ya une documentation de référence pour toute les APIs high-level et low-level dans le SDK.

+ +

Et en suite?

+ +

Pour avoir une idée de certaines des choses que vous pouvez faire avec les API du SDK, essayer de travailler avec certains tutoriels.

diff --git a/files/fr/mozilla/add-ons/sdk/tutorials/index.html b/files/fr/mozilla/add-ons/sdk/tutorials/index.html new file mode 100644 index 0000000000..d68fcfd2ac --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tutorials/index.html @@ -0,0 +1,143 @@ +--- +title: Tutoriels +slug: Mozilla/Add-ons/SDK/Tutorials +tags: + - Add-on SDK + - TopicStub +translation_of: Archive/Add-ons/Add-on_SDK/Tutorials +--- +

Cette page répertorie les articles sur la façon d'accomplir des tâches spécifiques en utilisant le SDK.

+ +
+

Commencer

+ +
+
+
+
Installation
+
Comment faire pour installer l'outil de jpm, que vous allez utiliser pour développer des add-ons.
+
+ +
+
Dépannage
+
Quelques conseils pour résoudre les problèmes courants et obtenir de l'aide.
+
+
+ +
+
+
Commencer
+
Démonstration de la création d'une add-on avec le SDK, en utilisant jpm.
+
+
+
+ +
+

Créer des interfaces utilisateur

+ +
+
+
+
Ajouter un bouton de barre d'outils
+
Attachez un bouton à la barre d'outils du module complémentaire Firefox.
+
Ajouter un élément de menu à Firefox
+
Ajoutez des éléments aux menus principaux de Firefox.
+
+
+ +
+
+
Afficher une popup
+
Afficher une boîte de dialogue contextuelle (popup) implémentée avec HTML et JavaScript.
+
Ajouter un élément de menu contextuel
+
Ajoutez des éléments au menu contextuel de Firefox.
+
+
+
+ +
+

Interagir avec le navigateur

+ +
+
+
+
Ouvrir une page Web
+
Ouvrez une page Web dans un nouvel onglet ou une nouvelle fenêtre du navigateur à l'aide du module onglets et accédez à son contenu.
+
Écouter le chargement de la page
+
Utilisez le module onglets pour être averti lorsque de nouvelles pages Web sont chargées et accéder à leur contenu.
+
+
+ +
+
+
Obtenir la liste des onglets ouverts
+
Utilisez le module onglets pour parcourir les onglets actuellement ouverts et accéder à leur contenu.
+
+
+
+ +
+

Modifier les pages Web

+ +
+
+
+
Modifier les pages Web en fonction de l'URL
+
Créez des filtres pour les pages Web en fonction de leur URL: chaque fois qu'une page Web dont l'URL correspond au filtre est chargée, exécutez un script spécifié.
+
+
+ +
+
+
Modifier la page Web active
+
Chargez dynamiquement un script dans la page Web actuellement active.
+
+
+
+ +
+

Techniques de développement

+ +
+
+
+
Enregistrement
+
Enregistrez les messages sur la console à des fins de diagnostic.
+
Création de modules réutilisables
+
Structurez votre module complémentaire en modules séparés pour faciliter le développement, le débogage et la maintenance. Créez des paquets réutilisables contenant vos modules, afin que d'autres développeurs de modules complémentaires puissent également les utiliser.
+
Tests unitaires
+
Ecrire et exécuter des tests unitaires à l'aide du framework de test du SDK.
+
Autorité Chrome
+
Accédez à l'objet Components, permettant à votre module complémentaire de charger et d'utiliser n'importe quel objet XPCOM.
+
Création de cibles d'événements
+
Permettez aux objets que vous définissez d'émettre leurs propres événements.
+
+
+ +
+
+
Écouter pour charger et décharger
+
Recevez des notifications lorsque votre module complémentaire est chargé ou déchargé par Firefox, et passez des arguments dans votre module complémentaire à partir de la ligne de commande.
+
Utilisation de modules tiers (jpm)
+
Installez et utilisez des modules supplémentaires qui ne sont pas fournis avec le SDK lui-même.
+
Localisation
+
Écriture de code localisable.
+
Développement mobile
+
Développez des modules complémentaires pour Firefox Mobile sur Android.
+
Débogueur de module complémentaire (Add-on)
+
Déboguez le JavaScript de votre module complémentaire.
+
+
+
+ +
+

Mettre ensemble

+ +
+
+
+
Module complémentaire Annotator
+
Présentation d'un module complémentaire relativement complexe.
+
+
+
diff --git a/files/fr/mozilla/add-ons/sdk/tutorials/l10n/index.html b/files/fr/mozilla/add-ons/sdk/tutorials/l10n/index.html new file mode 100644 index 0000000000..4b9ca669e7 --- /dev/null +++ b/files/fr/mozilla/add-ons/sdk/tutorials/l10n/index.html @@ -0,0 +1,383 @@ +--- +title: Localisation +slug: Mozilla/Add-ons/SDK/Tutorials/l10n +translation_of: Archive/Add-ons/Add-on_SDK/Tutorials/l10n +--- +

Le SDK supporte la localisation des chaînes figurant dans:

+ + + +

Il ne le fait pas dans le CSS, les scripts anexe, ou les champs titre et description qui apparaissent dans le gestionnaire de modules complémentaires. Voir Limitations ci-dessous.

+ +

Chaînes localisées

+ +

Les chaînes traduites sont conservées dans un répertoire appelé "locale" sous votre répertoire principale de l'add-on , avec un fichier pour chaque langue. Les dossiers:

+ + + +

Supposons que votre add-on contient une seule chaîne localisable, représentée en anglais comme "Hello!", Et que vous souhaitez fournir les localisations Français FRANCAIS et anglais ETATS-UNIS.

+ +

Vous souhaitez ajouter deux fichiers au répertoire "locale" :

+ +
my-addon/
+         data
+         lib
+         locale/
+                en-US.properties
+                fr.properties
+
+ +

"en-US.properties" contient ceci:

+ +
hello_id= Hello!
+
+ +

"fr.properties" contient ceci:

+ +
hello_id= Bonjour!
+
+ +

Maintenant, chaque fois que votre JavaScript ou HTML demande au système de localisation la traduction de l'identifiant hello_id, il obtiendra la traduction correcte pour la localisation en cours.

+ +

Utilisation de chaînes localisées en HTML

+ +
+

Cet exemple utilise l'API button_action, qui est uniquement disponible à partir de Firefox 29.

+
+ +

Pour référencer des chaînes localisées du HTML, ajouter un attribut data-l10n-id à la balise HTML où vous voulez que la chaîne localisée apparaisse, et assignez y l'identifiant :

+ +
<html>
+  <body>
+    <h1 data-l10n-id="hello_id"></h1>
+  </body>
+</html>
+
+ +

Ensuite, vous pouvez utiliser ce fichier HTML pour construire votre interface, par exemple à l'intérieur d'un panel :

+ +
var button = require("sdk/ui/button/action").ActionButton({
+  id: "localized-hello",
+  label: "Localized hello",
+  icon: "./icon-16.png",
+  onClick: function() {
+    hello.show();
+  }
+});
+
+var hello = require("sdk/panel").Panel({
+  height: 75,
+  width: 150,
+  contentURL: require("sdk/self").data.url("my-panel.html")
+});
+ +

Compte tenu de fichiers locaux pour "en-US" et "fr" qui fournissent les traductions de hello_id, le panneau affichera désormais "Bonjour!" ou "Hello!", selon la localisation en cours:

+ +

+ +

La traduction est inséré dans le nœud qui a l'attribut data-l10n-id défini. Tout contenu existant précédemment est simplement remplacé.

+ +

La chaîne est insérée sous forme de texte, de sorte que vous ne pouvez pas insérer du code HTML en utilisant une déclaration comme:

+ +
# Ne fonctionne pas. Les balises HTML sont insérés sous forme de texte.
+hello_id= <blink>Hello!</blink>
+
+ +

Attributs d'Elément Localisation

+ +
Cette fonction est nouvelle dans Firefox 39
+ +

Vous pouvez localiser certains attributs d'éléments avec un l10n-id en définissant sa valeur avec l10n-id.attributeName dans le fichier de propriétés comme:

+ +
hello_id.accesskey= H
+ +

Les attributs suivants sont supportés:

+ + + +

En outre, la localisation avec les attributs ARIA aria-label , aria-valuetex et aria-moz-hint sont pris en charge avec les mêmes alias que sur Firefox OS :

+ + + +

Utilisation de chaînes localisées en JavaScript

+ +

Pour référencer les chaînes localisées à partir de votre code d'add-on principale, faites ceci:

+ +
var _ = require("sdk/l10n").get;
+console.log(_("hello_id!"));
+ +

L'affectation de "_" n'est pas nécessaire, mais pour travailler avec les outils gettext qui attendent "_" pour indiquer les chaînes localisables, cela est préférable.

+ +
    +
  1. Importez le module l10n, et assigner sa fonction get à "_"(underscore).
  2. +
  3. Enveloppez toutes les références aux chaînes localisables avec la fonction _().
  4. +
+ +

Si vous l'exécutez, vous verrez le résultat attendu pour la localisation en cours:

+ +
info: Hello!
+
+ +
info: Bonjour!
+
+ +

Notez que parce que vous ne pouvez pas appeler des modules avec require() dans les content_scripts, vous ne pouvez pas encore référencer les chaînes localisées à partir des content_scripts.

+ +

Pluriels

+ +

Le module l10n prend en charge les formes plurielles. Plusieurs langues ont des règles différentes pour la formation des pluriels. Par exemple, l'anglais a deux formes: une forme singulière pour "un", et une forme plurielle pour "tout le reste, y compris zéro":

+ +
one tomato
+no tomatoes
+two tomatoes
+
+ +

Mais le Russe a des formes différentes pour les numéros se terminant par 1 (sauf 11), numéros se terminant par 2-4 (sauf 12-14) et les autres numéros:

+ +
один помидор     // one tomato
+два помидора     // two tomatoes
+пять помидоров   // five tomatoes
+
+ +

Le SDK utilise les données de Unicode CLDR pour décrire les différentes formes plurielles utilisés dans les différentes langues.

+ +

Formes plurielles de Unicode CLDR

+ +

Le projet Unicode CLDR définit un schéma pour décrire les règles de pluriel d'une langue particulière. Dans ce schéma, une langue peut se distinguer par un maximum de six formes, identifié par les catégories suivantes : zero, one, two, few, many et other.

+ +

L'englais a deux formes, qui peuvent être décrits par les categories "1" à "one" et "everything else" à "other":

+ +
one   → n is 1;
+other → everything else
+
+ +

Le russe utilise quatre formes, qui peuvent être décrits comme suit:

+ +
one   → n mod 10 is 1 and n mod 100 is not 11;
+few   → n mod 10 in 2..4 and n mod 100 not in 12..14;
+many  → n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14;
+other → everything else
+
+ +

Les règles de pluriel pour toutes les langues peuvent être trouvés dans le CLDR Langue règles pluriel (ce tableau est mis à jour par rapport à la source XML CLDR).

+ +

Formes plurielles dans le SDK

+ +

Dans le code, vous pouvez fournir un paramètre supplémentaire à côté de l'identifiant, en décrivant combien d'articles il y a :

+ +
var _ = require("sdk/l10n").get;
+console.log(_("tomato_id"));
+console.log(_("tomato_id", 1));
+console.log(_("tomato_id", 2));
+console.log(_("tomato_id", 5));
+console.log(_("tomato_id", .5));
+ +

Dans le fichier .properties pour chaque langue, vous pouvez définir une localisation différente pour chaque forme plurielle possible dans cette langue, en utilisant les mots-clés de CLDR. Donc, en anglais, nous pourrions avoir deux localisations pluriel (à noter que la catégorie «other» ne prendre pas le mot-clé CLDR):

+ +
# en-US translations
+tomato_id[one]= %d tomato
+tomato_id= %d tomatoes
+
+ +

En Russe, nous pourrions avoir quatre localisations pluriel:

+ +
# ru-RU translations
+tomato_id[one]= %d помидор
+tomato_id[few]= %d помидора
+tomato_id[many]= %d помидоров
+tomato_id= %d помидоры
+
+ +

Le module de localisation comprend les définitions de CLDR pour chaque langue, ce qui lui permet de faire la différence entre, par exemple, "2" dans le code et "few" dans ru-RU.properties. Ensuite, il récupère et renvoie la localisation pour le compte que vous avez fourni.

+ +

Espaces réservés

+ +

Le module l10n prend en charge des espaces réservés, vous permettant d'insérer une chaîne qui ne devrait pas être localisé. Dans le code qui suit les fichiers "en-US" et "fr" ".properties" incluent des espaces réservés :

+ +
# en-US translations
+hello_id= Hello %s!
+
+ +
# fr translations
+hello_id= Bonjour %s !
+
+ +

Pour utiliser les espaces réservés, fournir la chaîne de réservation après l'identifiant:

+ +
var _ = require("sdk/l10n").get;
+console.log(_("hello_id", "Bob"));
+console.log(_("hello_id", "Alice"));
+ +

Dans la localisation "en-US", cela nous donne:

+ +
info: Hello Bob!
+info: Hello Alice!
+
+ +

Dans "fr" nous obtenons:

+ +
info: Bonjour Bob !
+info: Bonjour Alice !
+
+ +

Commande espaces réservés

+ +

Quand une chaîne localisable peut prendre deux ou plusieurs espaces réservés, les traducteurs peuvent définir l'ordre dans lequel les espaces réservés sont insérés, sans affecter le code.

+ +

Principalement, ce qui est important c'est que les différentes langues ont des règles différentes pour l'ordre des mots. Même au sein de la même langue, cependant, les traducteurs doivent avoir la liberté de définir l'ordre des mots.

+ +

Par exemple, supposons que nous voulons inclure une chaîne localisée nommer ville natale d'une personne. Il y a deux espaces réservés: le nom de la personne et le nom de la ville natale :

+ +
var _ = require("sdk/l10n").get;
+console.log(_("home_town_id", "Bob", "London"));
+ +

Un traducteur anglais pourrait vouloir choisir entre les ordres suivantes:

+ +
"<town_name> is <person_name>'s home town."
+
+ +
"<person_name>'s home town is <town_name>"
+
+ +

Pour choisir la première option, le fichier .properties peut commander les espaces réservés comme suit:

+ +
home_town_id= %2s is %1s's home town.
+
+ +

Cela nous donne le résultat suivant:

+ +
info: London is Bob's home town.
+
+ +

Utilisation de chaînes localisées dans les Préférences

+ +

En incluant une structure "preferences" dans votre fichier "package.json", vous pouvez définir des préférences pour votre add-on que l'utilisateur peut voir et modifier à l'aide de Firefox Add-ons Manager.

+ +

Les préférences ont obligatoirement des champs title et description. Ce sont des chaînes qui apparaissent aux côtés de la préférence dans le Gestionnaire Add-ons, pour expliquer à l'utilisateur ce que signifie la préférence.

+ + + +

Par exemple, supposons que votre "package.json" définit une seule préférence:

+ +
{
+    "preferences": [
+        {
+            "type": "string",
+            "name": "monster_name",
+            "value": "Gerald",
+            "title": "Name"
+        }
+    ],
+    "name": "monster-builder",
+    "license": "MPL 2.0",
+    "author": "me",
+    "version": "0.1",
+    "fullName": "Monster Builder",
+    "id": "monster-builder@me.org",
+    "description": "Build your own monster"
+}
+
+ +

Dans votre fichier "en-US.properties", inclure ces deux éléments :

+ +
monster_name_title= Name
+monster_name_description= What is the monster's name?
+
+ +

Dans votre fichier "fr.properties", inclure la traduction française:

+ +
monster_name_title= Nom
+monster_name_description= Quel est le nom du monstre ?
+
+ +

Quand la configuration locale du navigateur est "en-US", les utilisateurs voient dans le gestionnaire de modules complémentaires:

+ +

+ +

Lorsque la configuration locale du navigateur est "fr", ils voient ceci:

+ +

+ +

Les types menulist et radio de préférences ont des options. L'attribut label de chaque option est affichée à l'utilisateur. Si le fichier de paramètres régionaux a une entrée avec la valeur de l'élément label préfixé «{name}_options." comme clé (où {name} est le nom de la préférence), sa valeur est utilisée comme étiquette localisée.

+ +

Utilisation de l'identificateurs

+ +

Si le système de localisation ne peut pas trouver une entrée pour un identifiant particulier en utilisant la localisation en cours, elle retourne juste l'identifiant lui-même.

+ +

C'est intéressante car vous pouvez écrire du code "localisable", entièrement fonctionnel sans avoir à écrire des fichiers locaux. Vous pouvez simplement utiliser les chaînes de langue par défaut et fournir ultérieurement les fichiers .properties pour toutes les langues supplémentaires que vous souhaitez soutenir.

+ +

Par exemple, dans le cas ci-dessus, vous pouvez utiliser "Bonjour!" comme identificateur, et juste avoir un .properties pour la locale "fr":

+ +
Hello!= Bonjour!
+
+ +

Puis, quand la locale "en-US", le système ne parviennent pas à trouver un .properties, et revoit "Bonjour!".

+ +
+

Cependant, cette approche rend difficile le maintien d'une add-on qui a de nombreuses localisations, parce que vous utilisez les chaînes de langue par défaut en tant que chaînes de l'interface utilisateur et que les clés recherchent vos traductions. Cela signifie que si vous voulez changer le libellé d'une chaîne dans la langue par défaut, ou corriger une faute de frappe, alors vous cassez tous vos fichiers de paramètres régionaux.

+
+ +

Locale Updater

+ +

L'add-on locale updater (paramètres régionaux de mise à jour) rend plus facile la mise à jour des fichiers locaux. Une fois que vous l'avez installé, ouvrez le Gestionnaire de modules complémentaires, et vous verrez un nouveau bouton "Update l10n" à côté de chaque add-on que vous avez installé :

+ +

+ +

Cliquez sur le bouton et vous serez invité à entrer un nouveau fichier .properties pour cette add-on. Si vous fournissez un nouveau fichier, les données locales de l'add-on seront mis à jour avec le nouveau fichier.

+ +

Limites

+ +

Le support de la localisation actuelle est un premier pas vers la prise en charge complète, et contient un certain nombre de limitations.

+ + + +

Voir aussi - pour les développeurs qui cherchent à localiser les add-ons non-SDK

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