From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- .../a_sua_primeira_extensao/index.html | 153 ------- .../a_sua_segunda_extensao/index.html | 460 --------------------- .../anatomia_de_uma_extensao/index.html | 135 ------ .../anatomy_of_a_webextension/index.html | 135 ++++++ .../webextensions/api/armazenamento/index.html | 105 ----- .../webextensions/api/devtools.panels/index.html | 103 ----- .../webextensions/api/devtools/panels/index.html | 103 +++++ .../add-ons/webextensions/api/storage/index.html | 105 +++++ .../index.html | 159 ------- .../browser_support_for_javascript_apis/index.html | 19 + .../webextensions/content_scripts/index.html | 446 ++++++++++++++++++++ .../index.html | 81 ---- .../webextensions/dubla_padr\303\265es/index.html" | 430 ------------------- .../add-ons/webextensions/e_a_seguir/index.html | 60 --- .../add-ons/webextensions/examples/index.html | 28 ++ .../webextensions/exemplos_extensoes/index.html | 28 -- .../extending_the_developer_tools/index.html | 156 +++++++ .../extennsoesweb_e_a_id_do_extra/index.html | 78 ---- .../index.html" | 156 ------- .../instalacao_temporaria_no_firefox/index.html | 50 --- .../intercept_http_requests/index.html | 160 +++++++ .../interceptar_pedidos_http/index.html | 160 ------- .../acoes_pagina/index.html | 50 --- .../a\303\247\303\243o_navegador/index.html" | 50 --- .../barras_laterais/index.html | 57 --- .../devtools_panels/index.html | 62 --- .../estilos_de_navegador/index.html | 453 -------------------- .../interface_do_utilizador/index.html | 93 ----- .../itens_do_menu_de_contexto/index.html | 51 --- .../notificacoes/index.html | 50 --- .../interface_do_utilizador/omnibox/index.html | 70 ---- .../options_pages/index.html | 64 --- .../paginas_de_extens\303\243o/index.html" | 64 --- .../interface_do_utilizador/popups/index.html | 60 --- .../webextensions/manifest.json/icones/index.html | 78 ---- .../webextensions/manifest.json/icons/index.html | 78 ++++ .../webextensions/match_patterns/index.html | 430 +++++++++++++++++++ .../o_que_sao_webextensions/index.html | 59 --- .../primeiros_passos_com_web-ext/index.html | 304 -------------- .../publicar_a_sua_extensao/index.html | 62 --- .../webextensions/scripts_conteudo/index.html | 446 -------------------- .../suporte_navegador_apis_javascript/index.html | 19 - .../trasnsferir_extensao_google_chrome/index.html | 22 - .../user_interface/browser_action/index.html | 50 +++ .../user_interface/browser_styles/index.html | 453 ++++++++++++++++++++ .../user_interface/context_menu_items/index.html | 51 +++ .../user_interface/devtools_panels/index.html | 62 +++ .../user_interface/extension_pages/index.html | 64 +++ .../webextensions/user_interface/index.html | 93 +++++ .../user_interface/notifications/index.html | 50 +++ .../user_interface/omnibox/index.html | 70 ++++ .../user_interface/options_pages/index.html | 64 +++ .../user_interface/page_actions/index.html | 50 +++ .../webextensions/user_interface/popups/index.html | 60 +++ .../user_interface/sidebars/index.html | 57 +++ .../what_are_webextensions/index.html | 59 +++ .../add-ons/webextensions/what_next_/index.html | 60 +++ .../your_first_webextension/index.html | 153 +++++++ .../your_second_webextension/index.html | 460 +++++++++++++++++++++ 59 files changed, 3516 insertions(+), 4272 deletions(-) delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/examples/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html (limited to 'files/pt-pt/mozilla/add-ons/webextensions') diff --git a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html deleted file mode 100644 index 21b34f2e2c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: A sua primeira extensão -slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao -tags: - - Extensões da Web - - Guía -translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension ---- -
{{AddonSidebar}}
- -

Neste artigo, nós iremos abordar a criação de uma extensão para o Firefox, do início até ao fim. A extensão adiciona apenas um contorno vermelho a qualquer página carregada de 'mozilla.org' ou qualquer um dos seus subdomínios.

- -

O código fonte para este exemplo está no GitHub: borderify.

- -

Primeiro, precisa de ter o Firefox - versão 45 ou superior.

- -

Escrever a extensão

- -

Crie uma nova diretoria e vá para a mesma:

- -
mkdir borderify
-cd borderify
- -

manifest.json

- -

Now create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Borderify",
-  "version": "1.0",
-
-  "description": "Adds a red border to all webpages matching mozilla.org.",
-
-  "icons": {
-    "48": "icons/border-48.png"
-  },
-
-  "content_scripts": [
-    {
-      "matches": ["*://*.mozilla.org/*"],
-      "js": ["borderify.js"]
-    }
-  ]
-
-}
- - - -

The most interesting key here is content_scripts, which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains.

- - - -
-

In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the  applications key in manifest.json and set its gecko.id property:

- -
"applications": {
-  "gecko": {
-    "id": "borderify@example.com"
-  }
-}
-
- -

icons/border-48.png

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png".

- -

Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png".  You could use the one from our example, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/border-48.png",
-  "96": "icons/border-96.png"
-}
- -

Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.)

- - - -

borderify.js

- -

Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content:

- -
document.body.style.border = "5px solid red";
- -

This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself.

- - - -

Testá-la

- -

Primeiro, reverifique que tem os ficheiros corretos nos locais certos:

- -
borderify/
-    icons/
-        border-48.png
-    borderify.js
-    manifest.json
- -

Instalar

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on" and select any file in your extension's directory:

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

The extension will now be installed, and will stay until you restart Firefox.

- -

Alternatively, you can run the extension from the command line using the web-ext tool.

- -

Testar

- -

Now try visiting a page under "mozilla.org", and you should see the red border round the page:

- -

{{EmbedYouTube("rxBQl2Z9IBQ")}}

- -
-

Don't try it on addons.mozilla.org, though! Content scripts are currently blocked on that domain.

-
- -

Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extensions's files by clicking the "Reload" button in about:debugging. You can see the changes right away:

- -

{{EmbedYouTube("NuajE60jfGY")}}

- - - -

Empacotar e publicação

- -

Para que as outras pessoas utilizem a sua extensão, precisa de empacotá-la e enviá-la para a assinar na Mozilla. Para saber mais sobre isto, consulte "Publicar a sua extensão".

- -

E a seguir?

- -

Agora tem uma idéia do processo de desenvolvimento de uma Extensão da Web para o Firefox, tente:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html deleted file mode 100644 index 503f2b4ae9..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html +++ /dev/null @@ -1,460 +0,0 @@ ---- -title: A sua segunda extensão -slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension ---- -
{{AddonSidebar}} -

Se já leu o artigo da A sua primeira extensão, já tem uma ideia de como escrever uma extensão. Neste artigo, nós iremos escrever uma extensão um pouco mais complexa que demonstra algumas mais das APIs. 
-
- A extensão adiciona um novo botão à barra de ferramentas do Firefox. Quando o utilizador clica no botão, nós exibimos uma janela que lhes permite escolher um animal. Uma vez que eles escolhem um animal, nós iremos substituir o conteúdo da página atual com uma fotografia do animal escolhido. 
-
- Para implementar isto, nós iremos:.

- -

To implement this, we will:

- - - -

You could visualise the overall structure of the extension like this:

- -

- -

It's a simple extension, but shows many of the basic concepts of the WebExtensions API:

- - - -

You can find complete source code for the extension on GitHub.

- -

To write this extension, you'll need Firefox 45 or newer.

- -

Escrever a extensão

- -

Create a new directory and navigate to it:

- -
mkdir beastify
-cd beastify
- -

manifest.json

- -

Now create a new file called "manifest.json", and give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Beastify",
-  "version": "1.0",
-
-  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
-  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
-  "icons": {
-    "48": "icons/beasts-48.png"
-  },
-
-  "permissions": [
-    "activeTab"
-  ],
-
-  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  },
-
-  "web_accessible_resources": [
-    "beasts/frog.jpg",
-    "beasts/turtle.jpg",
-    "beasts/snake.jpg"
-  ]
-
-}
-
- - - -

Note that all paths given are relative to manifest.json itself.

- -

O ícone

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png".

- -

Create the "icons" directory and save an icon there named "beasts-48.png".  You could use the one from our example, which is taken from the Aha-Soft’s Free Retina iconset, and used under the terms of its license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/beasts-48.png",
-  "96": "icons/beasts-96.png"
-}
- -

O botão de barra de ferramentas

- -

The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png".

- -

Save an icon named "beasts-32.png" in the "icons" directory. You could use the one from our example, which is taken from the IconBeast Lite icon set and used under the terms of its license.

- -

If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.

- -

A janela (popup)

- -

The function of the popup is to enable the user to choose one of three beasts.

- -

Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:

- - - -
mkdir popup
-cd popup
-touch choose_beast.html choose_beast.css choose_beast.js
-
- -

choose_beast.html

- -

The HTML file looks like this:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-    <link rel="stylesheet" href="choose_beast.css"/>
-  </head>
-
-<body>
-  <div id="popup-content">
-    <div class="button beast">Frog</div>
-    <div class="button beast">Turtle</div>
-    <div class="button beast">Snake</div>
-    <div class="button reset">Reset</div>
-  </div>
-  <div id="error-content" class="hidden">
-    <p>Can't beastify this web page.</p><p>Try a different page.</p>
-  </div>
-  <script src="choose_beast.js"></script>
-</body>
-
-</html>
-
- -

We have a <div> element with an ID of "popup-content" that contains an element for each animal choice. We have another <div> with an ID of "error-content" and a class "hidden". We'll use that in case there's a problem initializing the popup.

- -

Note that we include the CSS and JS files from this file, just like a web page.

- -

choose_beast.css

- -

The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with class="hidden": this means that our "error-content" <div> will be hidden by default.

- -
html, body {
-  width: 100px;
-}
-
-.hidden {
-  display: none;
-}
-
-.button {
-  margin: 3% auto;
-  padding: 4px;
-  text-align: center;
-  font-size: 1.5em;
-  cursor: pointer;
-}
-
-.beast:hover {
-  background-color: #CFF2F2;
-}
-
-.beast {
-  background-color: #E5F2F2;
-}
-
-.reset {
-  background-color: #FBFBC9;
-}
-
-.reset:hover {
-  background-color: #EAEA9D;
-}
-
-
- -

choose_beast.js

- -

Here's the JavaScript for the popup:

- -
/**
- * CSS to hide everything on the page,
- * except for elements that have the "beastify-image" class.
- */
-const hidePage = `body > :not(.beastify-image) {
-                    display: none;
-                  }`;
-
-/**
- * Listen for clicks on the buttons, and send the appropriate message to
- * the content script in the page.
- */
-function listenForClicks() {
-  document.addEventListener("click", (e) => {
-
-    /**
-     * Given the name of a beast, get the URL to the corresponding image.
-     */
-    function beastNameToURL(beastName) {
-      switch (beastName) {
-        case "Frog":
-          return browser.extension.getURL("beasts/frog.jpg");
-        case "Snake":
-          return browser.extension.getURL("beasts/snake.jpg");
-        case "Turtle":
-          return browser.extension.getURL("beasts/turtle.jpg");
-      }
-    }
-
-    /**
-     * Insert the page-hiding CSS into the active tab,
-     * then get the beast URL and
-     * send a "beastify" message to the content script in the active tab.
-     */
-    function beastify(tabs) {
-      browser.tabs.insertCSS({code: hidePage}).then(() => {
-        let url = beastNameToURL(e.target.textContent);
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "beastify",
-          beastURL: url
-        });
-      });
-    }
-
-    /**
-     * Remove the page-hiding CSS from the active tab,
-     * send a "reset" message to the content script in the active tab.
-     */
-    function reset(tabs) {
-      browser.tabs.removeCSS({code: hidePage}).then(() => {
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "reset",
-        });
-      });
-    }
-
-    /**
-     * Just log the error to the console.
-     */
-    function reportError(error) {
-      console.error(`Could not beastify: ${error}`);
-    }
-
-    /**
-     * Get the active tab,
-     * then call "beastify()" or "reset()" as appropriate.
-     */
-    if (e.target.classList.contains("beast")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(beastify)
-        .catch(reportError);
-    }
-    else if (e.target.classList.contains("reset")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(reset)
-        .catch(reportError);
-    }
-  });
-}
-
-/**
- * There was an error executing the script.
- * Display the popup's error message, and hide the normal UI.
- */
-function reportExecuteScriptError(error) {
-  document.querySelector("#popup-content").classList.add("hidden");
-  document.querySelector("#error-content").classList.remove("hidden");
-  console.error(`Failed to execute beastify content script: ${error.message}`);
-}
-
-/**
- * When the popup loads, inject a content script into the active tab,
- * and add a click handler.
- * If we couldn't inject the script, handle the error.
- */
-browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
-.then(listenForClicks)
-.catch(reportExecuteScriptError);
-
-
- -

The place to start here is line 96. The popup script executes a content script in the active tab as soon as the popup is loaded, using the browser.tabs.executeScript() API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page.

- -

A common reason the browser.tabs.executeScript() call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the addons.mozilla.org domain. If it does fail, reportExecuteScriptError() will hide the "popup-content" <div>, show the "error-content" <div>, and log an error to the console.

- -

If executing the content script is successful, we call listenForClicks(). This listens for clicks on the popup.

- - - -

The beastify() function does three things:

- - - -

The reset() function essentially undoes a beastify:

- - - -

O script de conteúdo

- -

Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents:

- -
(function() {
-  /**
-   * Check and set a global guard variable.
-   * If this content script is injected into the same page again,
-   * it will do nothing next time.
-   */
-  if (window.hasRun) {
-    return;
-  }
-  window.hasRun = true;
-
-  /**
-   * Given a URL to a beast image, remove all existing beasts, then
-   * create and style an IMG node pointing to
-   * that image, then insert the node into the document.
-   */
-  function insertBeast(beastURL) {
-    removeExistingBeasts();
-    let beastImage = document.createElement("img");
-    beastImage.setAttribute("src", beastURL);
-    beastImage.style.height = "100vh";
-    beastImage.className = "beastify-image";
-    document.body.appendChild(beastImage);
-  }
-
-  /**
-   * Remove every beast from the page.
-   */
-  function removeExistingBeasts() {
-    let existingBeasts = document.querySelectorAll(".beastify-image");
-    for (let beast of existingBeasts) {
-      beast.remove();
-    }
-  }
-
-  /**
-   * Listen for messages from the background script.
-   * Call "beastify()" or "reset()".
-  */
-  browser.runtime.onMessage.addListener((message) => {
-    if (message.command === "beastify") {
-      insertBeast(message.beastURL);
-    } else if (message.command === "reset") {
-      removeExistingBeasts();
-    }
-  });
-
-})();
-
- -

The first thing the content script does is to check for a global variable window.hasRun: if it's set the script returns early, otherwise it sets window.hasRun and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything.

- -

After that, the place to start is line 40, where the content script listens for messages from the popup, using the browser.runtime.onMessage API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".

- - - -

As feras

- -

Finally, we need to include the images of the beasts.

- -

Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from the GitHub repository, or from here:

- -

- -

Testar a extensão

- -

First, double check that you have the right files in the right places:

- -
beastify/
-
-    beasts/
-        frog.jpg
-        snake.jpg
-        turtle.jpg
-
-    content_scripts/
-        beastify.js
-
-    icons/
-        beasts-32.png
-        beasts-48.png
-
-    popup/
-        choose_beast.css
-        choose_beast.html
-        choose_beast.js
-
-    manifest.json
- -

Starting in Firefox 45, you can install extensions temporarily from disk.

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your manifest.json file. You should then see the extension's icon appear in the Firefox toolbar:

- -

{{EmbedYouTube("sAM78GU4P34")}}

- -

Open a web page, then click the icon, select a beast, and see the web page change:

- -

{{EmbedYouTube("YMQXyAQSiE8")}}

- -

Programae a partir da linha de comando

- -

Pode automatizar o passo da instalação temporária utilizando a ferramenta web-ext. Experimente isto:

- -
cd beastify
-web-ext run
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html deleted file mode 100644 index ecad403ae1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Anatomia de uma extensão -slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension ---- -
{{AddonSidebar}}
- -

Uma extensão consiste numa coleção de ficheiros, empacotados para distribuição e instalação. Neste artigo, nós passaremos rapidamente pelos ficheiros que podem estar presentes numa extensão.

- -

manifest.json

- -

This is the only file that must be present in every extension. It contains basic metadata such as its name, version and the permissions it requires. It also provides pointers to other files in the extension.

- -

This manifest can also contain pointers to several other types of files:

- - - -

- -

See the manifest.json reference page for all the details.

- -

Other than those referenced from the manifest, an extension can include additional Extension pages with supporting files.

- -

Scripts de fundo (segundo plano)

- -

Extensions often need to maintain long-term state or perform long-term operations independently of the lifetime of any particular web page or browser window. That is what background scripts are for.

- -

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

- -

Especificar os scripts de fundo

- -

You can include a background script using the background key in "manifest.json":

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

You can specify multiple background scripts: if you do, they run in the same context, just like multiple scripts that are loaded into a single web page.

- -

Ambiente de script de fundo

- -

APIS de DOM

- -

Background scripts run in the context of special pages called background pages. This gives them a window global, along with all the standard DOM APIs provided by that object.

- -

You do not have to supply your background page. If you include a background script, an empty background page will be created for you.

- -

However, you can choose to supply your background page as a separate HTML file:

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

APIs da Extensão da Web

- -

Background scripts can use any of the WebExtension APIs in the script, as long as their extension has the necessary permissions.

- -

Acesso cruzado da origem

- -

Background scripts can make XHR requests to any hosts for which they have host permissions.

- -

Conteúdo da Web

- -

Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and can communicate with these content scripts using a message-passing API.

- -

Política de segurança do conteúdo

- -

Background scripts are restricted from certain potentially dangerous operations, like the use of eval(), through a Content Security Policy. See Content Security Policy for more details on this.

- -

Barras laterais, janelas (popups), opções de páginas

- -

A sua extensão pode inclur vários componentes da interface do utilizador cujo conteúdo é definido utilizando um documento HTML:

- - - -

For each of these components, you create an HTML file and point to it using a specific property in manifest.json. The HTML file can include CSS and JavaScript files, just like a normal web page.

- -

All of these are a type of Extension pages, and unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. They can even directly access variables in the background page using {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

- -

Páginas de extensão

- -

You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in manifest.json. However, they do also get access to all the same privileged WebExtension APIs as your background script.

- -

You'd typically load a page like this using {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.

- -

See Extension pages to learn more.

- -

Scripts de conteúdo

- -

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

- -

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

- -

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

- -

Unlike normal page scripts, they can:

- - - -

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

- -

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

- -

See the content scripts article to learn more.

- -

Recursos de acessibilidade da Web

- -

Web accessible resources are resources such as images, HTML, CSS, and JavaScript that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme.

- -

For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append img tags which reference the images via the src attribute.

- -

To learn more, see the documentation for the web_accessible_resources manifest.json key.

- -

 

- -

 

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html new file mode 100644 index 0000000000..ecad403ae1 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html @@ -0,0 +1,135 @@ +--- +title: Anatomia de uma extensão +slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +--- +
{{AddonSidebar}}
+ +

Uma extensão consiste numa coleção de ficheiros, empacotados para distribuição e instalação. Neste artigo, nós passaremos rapidamente pelos ficheiros que podem estar presentes numa extensão.

+ +

manifest.json

+ +

This is the only file that must be present in every extension. It contains basic metadata such as its name, version and the permissions it requires. It also provides pointers to other files in the extension.

+ +

This manifest can also contain pointers to several other types of files:

+ + + +

+ +

See the manifest.json reference page for all the details.

+ +

Other than those referenced from the manifest, an extension can include additional Extension pages with supporting files.

+ +

Scripts de fundo (segundo plano)

+ +

Extensions often need to maintain long-term state or perform long-term operations independently of the lifetime of any particular web page or browser window. That is what background scripts are for.

+ +

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

+ +

Especificar os scripts de fundo

+ +

You can include a background script using the background key in "manifest.json":

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

You can specify multiple background scripts: if you do, they run in the same context, just like multiple scripts that are loaded into a single web page.

+ +

Ambiente de script de fundo

+ +

APIS de DOM

+ +

Background scripts run in the context of special pages called background pages. This gives them a window global, along with all the standard DOM APIs provided by that object.

+ +

You do not have to supply your background page. If you include a background script, an empty background page will be created for you.

+ +

However, you can choose to supply your background page as a separate HTML file:

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

APIs da Extensão da Web

+ +

Background scripts can use any of the WebExtension APIs in the script, as long as their extension has the necessary permissions.

+ +

Acesso cruzado da origem

+ +

Background scripts can make XHR requests to any hosts for which they have host permissions.

+ +

Conteúdo da Web

+ +

Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and can communicate with these content scripts using a message-passing API.

+ +

Política de segurança do conteúdo

+ +

Background scripts are restricted from certain potentially dangerous operations, like the use of eval(), through a Content Security Policy. See Content Security Policy for more details on this.

+ +

Barras laterais, janelas (popups), opções de páginas

+ +

A sua extensão pode inclur vários componentes da interface do utilizador cujo conteúdo é definido utilizando um documento HTML:

+ + + +

For each of these components, you create an HTML file and point to it using a specific property in manifest.json. The HTML file can include CSS and JavaScript files, just like a normal web page.

+ +

All of these are a type of Extension pages, and unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. They can even directly access variables in the background page using {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

+ +

Páginas de extensão

+ +

You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in manifest.json. However, they do also get access to all the same privileged WebExtension APIs as your background script.

+ +

You'd typically load a page like this using {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.

+ +

See Extension pages to learn more.

+ +

Scripts de conteúdo

+ +

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

+ +

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

+ +

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

+ +

Unlike normal page scripts, they can:

+ + + +

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

+ +

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

+ +

See the content scripts article to learn more.

+ +

Recursos de acessibilidade da Web

+ +

Web accessible resources are resources such as images, HTML, CSS, and JavaScript that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme.

+ +

For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append img tags which reference the images via the src attribute.

+ +

To learn more, see the documentation for the web_accessible_resources manifest.json key.

+ +

 

+ +

 

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html deleted file mode 100644 index d267faf520..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Armazenamento -slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento -tags: - - API - - Armazenamento - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/storage ---- -
{{AddonSidebar}}
- -

Permite que as extensões armazenem e recuperem dados, e escutem as alterações aos itens armazenados.

- -

O sistema de armazenamento é baseado na API de Armazenamento da Web, com algumas diferenças. Entre outras diferençãs, estas incluem:

- - - -

To use this API you need to include the "storage" permission in your manifest.json file.

- -

Each extension has its own storage area, which can be split into different types of storage.

- -

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

- -

Tipos

- -
-
{{WebExtAPIRef("storage.StorageArea")}}
-
An object representing a storage area.
-
{{WebExtAPIRef("storage.StorageChange")}}
-
An object representing a change to a storage area.
-
- -

Propriedades

- -

storage has three properties, which represent the different types of available storage area.

- -
-
{{WebExtAPIRef("storage.sync")}}
-
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
-
{{WebExtAPIRef("storage.local")}}
-
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
-
{{WebExtAPIRef("storage.managed")}}
-
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
-
- -

Eventos

- -
-
{{WebExtAPIRef("storage.onChanged")}}
-
Fired when one or more items change in a storage area.
-
- -

Compatibilidade do navegador

- -

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

- -

{{WebExtExamples("h2")}}

- -
Reconehcimentos - -

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

- -

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

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html deleted file mode 100644 index ebeb53d591..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: devtools.panels -slug: Mozilla/Add-ons/WebExtensions/API/devtools.panels -tags: - - API - - Extensões - - Extensões da Web - - Extras - - Referencia - - devtools.panels -translation_of: Mozilla/Add-ons/WebExtensions/API/devtools.panels ---- -
{{AddonSidebar}}
- -
-

Embora as APIs sejam baseadas no Chrome devtools APIs, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

The devtools.panels API lets a devtools extension define its user interface inside the devtools window.

- -

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

- -

With the devtools.panels API you can create new panels in the devtools window.

- -

Like all the devtools APIs, this API is only available to code running in the document defined in the devtools_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

- -

Tipos

- -
-
devtools.panels.ElementsPanel
-
Represents the HTML/CSS inspector in the browser's devtools.
-
devtools.panels.ExtensionPanel
-
Represents a devtools panel created by the extension.
-
devtools.panels.ExtensionSidebarPane
-
Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.
-
- -

Propriedades

- -
-
devtools.panels.elements
-
A reference to an ElementsPanel object.
-
devtools.panels.themeName
-
The name of the current devtools theme.
-
- -

Funções

- -
-
devtools.panels.create()
-
Creates a new devtools panel.
-
- -

Eventos

- -
-
devtools.panels.onThemeChanged
-
Fired when the devtools theme changes.
-
- -

Compatibilidade do navegador

- -

{{Compat("webextensions.api.devtools.panels", 2)}}

- -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.devtools.panels API.

- -

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

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html new file mode 100644 index 0000000000..ebeb53d591 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html @@ -0,0 +1,103 @@ +--- +title: devtools.panels +slug: Mozilla/Add-ons/WebExtensions/API/devtools.panels +tags: + - API + - Extensões + - Extensões da Web + - Extras + - Referencia + - devtools.panels +translation_of: Mozilla/Add-ons/WebExtensions/API/devtools.panels +--- +
{{AddonSidebar}}
+ +
+

Embora as APIs sejam baseadas no Chrome devtools APIs, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

+
+ +

The devtools.panels API lets a devtools extension define its user interface inside the devtools window.

+ +

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

+ +

With the devtools.panels API you can create new panels in the devtools window.

+ +

Like all the devtools APIs, this API is only available to code running in the document defined in the devtools_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

+ +

Tipos

+ +
+
devtools.panels.ElementsPanel
+
Represents the HTML/CSS inspector in the browser's devtools.
+
devtools.panels.ExtensionPanel
+
Represents a devtools panel created by the extension.
+
devtools.panels.ExtensionSidebarPane
+
Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.
+
+ +

Propriedades

+ +
+
devtools.panels.elements
+
A reference to an ElementsPanel object.
+
devtools.panels.themeName
+
The name of the current devtools theme.
+
+ +

Funções

+ +
+
devtools.panels.create()
+
Creates a new devtools panel.
+
+ +

Eventos

+ +
+
devtools.panels.onThemeChanged
+
Fired when the devtools theme changes.
+
+ +

Compatibilidade do navegador

+ +

{{Compat("webextensions.api.devtools.panels", 2)}}

+ +

{{WebExtExamples("h2")}}

+ +
Reconhecimentos + +

This API is based on Chromium's chrome.devtools.panels API.

+ +

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

+
+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html new file mode 100644 index 0000000000..d267faf520 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html @@ -0,0 +1,105 @@ +--- +title: Armazenamento +slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento +tags: + - API + - Armazenamento + - Extensões + - Extensões da Web + - Extras + - Interface + - Não Padrão + - Referencia +translation_of: Mozilla/Add-ons/WebExtensions/API/storage +--- +
{{AddonSidebar}}
+ +

Permite que as extensões armazenem e recuperem dados, e escutem as alterações aos itens armazenados.

+ +

O sistema de armazenamento é baseado na API de Armazenamento da Web, com algumas diferenças. Entre outras diferençãs, estas incluem:

+ + + +

To use this API you need to include the "storage" permission in your manifest.json file.

+ +

Each extension has its own storage area, which can be split into different types of storage.

+ +

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

+ +

Tipos

+ +
+
{{WebExtAPIRef("storage.StorageArea")}}
+
An object representing a storage area.
+
{{WebExtAPIRef("storage.StorageChange")}}
+
An object representing a change to a storage area.
+
+ +

Propriedades

+ +

storage has three properties, which represent the different types of available storage area.

+ +
+
{{WebExtAPIRef("storage.sync")}}
+
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
+
{{WebExtAPIRef("storage.local")}}
+
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
+
{{WebExtAPIRef("storage.managed")}}
+
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
+
+ +

Eventos

+ +
+
{{WebExtAPIRef("storage.onChanged")}}
+
Fired when one or more items change in a storage area.
+
+ +

Compatibilidade do navegador

+ +

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

+ +

{{WebExtExamples("h2")}}

+ +
Reconehcimentos + +

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

+ +

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

+
+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html deleted file mode 100644 index 0b3aba116e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: As melhores práticas de experiência do utilizador -slug: >- - Mozilla/Add-ons/WebExtensions/As_melhores_praticas_de_experiencia_do_utilizador -tags: - - Extensões - - Extras - - Guía - - IU - - UX -translation_of: Mozilla/Add-ons/WebExtensions/User_experience_best_practices ---- -
{{AddonSidebar()}}
- -

As melhores extensões do Firefox fornecem aos utilizadores uma nova funcionalidade ou recurso que corresponde a uma necessidade. Ao corresponder a essa necessidade irá ajudar os utilziadores a trabalhar de uma maneira mais inteligente ou eficiente, ou a obter mais prazer com a sua experiência de navegação.

- -

You will also want to make sure your users have a great experience using your extension and as a result give it great feedback and a good rating on addons.mozilla.org (AMO).

- -

Much has been written about what makes software usable. If you are new to the subject, a good place to start is Jakob Nielsen’s Usability Heuristics. We recommend, whether you are new to extension development or a seasoned pro, using Nielsen’s Heuristics as a checklist when testing your user experience (UX).

- -

So, here we discuss much more specific Firefox and browser extension UX features, offering advice and suggestions that will help you build an extension that delights your users.

- -

Seja Firefoxy

- -

Your users have chosen Firefox for a reason, possibly several reasons, so match your extension’s philosophy, features, and look and feel to that of Firefox.

- -

Design values

- -

To best meet the needs of Firefox users, align with the Firefox values.

- -

The Firefox Design Values state that we respect the user's privacy and sovereignty and do not surprise them. We start users with smart defaults on the functionality they want to use and enable them to customize those to their personal preferences so that they are in full control of their experience. We add humor and whimsy to our design and pay attention to details, quality, and performance. Local differences in a global world are important to us, and we help people make sense of the web in clear language.

- -

Apresentação e impressão

- -

To provide your extensions with the best long term fit to Firefox, align with the Firefox Photon Design System. Following Photon will ensure that your extension integrates with the Firefox experience and will make it easier for people to use.

- -

Mantenha-a focada

- -

An extension is best when it is centered around one main use case, addressing that use case as well as possible for the target audience. It should add one function or set of closely related functions to the browser, modify a function of the browser, or modify web pages. Determine if you have achieved this by asking whether you can easily communicate the features and purpose of the extension in three (short) sentences or less.

- -
-

A short summary description of your extension is also very useful when it comes to creating its listing on AMO, see Make sure your summary is just long enough for more details.

-
- -

Comece agora mesmo

- -

Ensure that your extension is ready to be used immediately after installation. It should be optimized for its main use case, and work as expected for most users without the need for customization.

- -

Do not expect your users to read detailed instructions, other content, or ask them to configure the extension to use it. Doing so could mean they never get started with your extension and, if they do, could result in poor reviews.

- -

Dê aos utilizadores o que eles precisam, onde eles precisam

- -

Choosing the right way or combination of ways to make your extension's functionality available to the user can have a significant effect on usability. Asking a few simple questions about your extension’s functionality can quickly guide you to the right choices:

- -

A minha extensão funciona na maioria dos sites da Web e páginas da Web?

- -

If your extension provides the user with features they can use on almost every website or page, give the user access to it from a toolbar button using the browser action. This might include providing access to your image editor or opening a page from your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão funciona apenas em alguns sites da Web e páginas?

- -

If your extension offers a feature for a type of web page or specific domains, give the user access to it from an address bar button using a page action. This might include providing access to your RSS reader on pages with RSS feeds or providing an extended feature to pages on your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão precisa de mostrar informação ou oferecer ações em paralelo com as páginas da Web?

- -

If your extension includes information or actions that a user would want immediate access to while viewing any web page, use a sidebar. This might include notes the user can make about a page’s content or a feature offering various font substitutions to improve readability.

- -



- -

A minha extensão oferece funcionalidade especifica para o conteúdo da página ou outras funcionalidades do navegador?

- -

If your extension offers features the user might want to access in context, add them to an appropriate context menu. This might include offering access to an image editor on the image context menu or offering extended copy features on the context menu for selected page content.

- -

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

- -

A minha extensão tem definições que o utilizador pode ajustar?

- -

If your extension enables the user to change and save settings that affect the behavior of the extension, use an options page to provide a standard Preferences link to settings from the Add-on Manager.

- -

Typical preferences button, to access an extension's settings, from the Add-on Manager

- -

A minha extensão precisa de recolher muita informação ou exibir conteúdo em adição aos separadores atuais?

- -

Where your extension needs to gather or display significant amounts of information (more than is suitable for an alert or would benefit from additional formatting) use bundled web pages to deliver forms and similar content.

- -

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

- -

A minha extensão tenta ajudar o utilizador a entrar as páginas da Web ou conteúdo?

- -

Where your extension includes a use case to locate web pages or content, for example, offering a site specific search, use address bar suggestions to deliver those recommendations.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

A minha extensão oferece ferramentas para os programadores?

- -

Where you are providing tools for developers, add them to the Firefox developer tools using developer tools panels.

- -

Mantenha o utilizador informado

- -

Ensuring the user knows what will happen, is happening, and has happened in your extension is an essential part of building trust and ensuring a happy user.

- -

Diga ao utilizador o que irá acontecer, antes que aconteça

- -

Users should understand what will happen when they click a button. In addition to a meaningful, descriptive button label, provide tooltips that describe the action that the button will perform.

- -
-

Do not put the name of the extension alone in the tooltip, unless it is descriptive of the action the button will perform.

-
- -

Do not use the tooltip for any other types of information such as elaborate statistics about your extension. Keep the tooltip content simple and focused on what will happen when the user clicks the button.

- -

Se é realmente importante e o utilizador afastou-se, notifique-os

- -

If your extension has completed a critical, long running background task, when the task completes use the operating system’s native notifications to update the user. This can be useful where the user may not be focusing on the extension, or the browser, when the process finishes. However, use sparingly. If it is sufficient for the user to discover that a process has completed when they return to the browser or extension, do not use notifications.

- -

- -

Utilizar browserAction badges sparingly

- -

You can add a badge over the toolbar icon of a browserAction, but do so sparingly to inform users about important events. Do not use them to provide regular or persistent status updates.

- -

When it comes to coloring a badge, using one of four colors for notifications of different severity is recommended:

- - - -
-

Use of Firefox colors is suggested, for more details see Firefox Colors. However, for compatibility with Chrome and Opera free color selection is supported.

-
- -

Testar, testar, e depois testar novamente

- -

Testing is a vital part of creating an outstanding UX for your extension. There are two key aspects of testing your UX:

- -
    -
  1. Test across devices and platforms to ensure your extension works and performs well in as many places as possible. This includes considering factors such as the user’s screen size and resolution—just because your extension looks good and is easy to use on your desktop monitor does not mean it looks as good and works as well on a smaller laptop screen, or, indeed, vice versa.
  2. -
  3. Test with as many users as possible. Do not assume that you know your audience, as people’s backgrounds and experience can make a huge difference to how they interact with your extension. So, allow for user testing as part of your extension’s development.
  4. -
- -

Dicas de teste:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html new file mode 100644 index 0000000000..e34a4013d3 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html @@ -0,0 +1,19 @@ +--- +title: Suporte de navegador para as APIs de JavaScript +slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +--- +

{{AddonSidebar}}

+ +
{{WebExtAllCompatTables}}
+ +
A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, verifique por favor, consulte https://github.com/mdn/browser-compat-data e envie-nos um pedido de submissão.
+ +
 
+ +
Agradecimentos + +

Os dados de compatibilidade do Microsoft Edge são fornecidos pela Corporação Microsoft e estão incluídos aqui sob a Licença de Creative Commons Attribution 3.0 - Estado Unidos.

+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html b/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..51356eed85 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,446 @@ +--- +title: Scripts de Conteúdo +slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +
{{AddonSidebar}}
+ +

Um script de conteúdo é uma parte da sua extensão que é executada no contexto de uma determinada página da Web (em oposição aos scripts de segundo plano que são parte da própria extensão, ou scripts que são parte do próprio site da Web, tal como aqueles carregados utilizando o {{HTMLElement("script")}} elemento.

+ +

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

+ +

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

+ +

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

+ +
+

Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a CSP error.

+ +

As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an onboarding page that moves users away from addons.mozilla.org.

+
+ +
+

Values added to the global scope of a content script with var foo or window.foo = "bar" may disappear due to bug 1408996.

+
+ +

Carregar scripts de conteúdo

+ +

You can load a content script into a web page in one of three ways:

+ +
    +
  1. at install time, into pages that match URL patterns: using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
  2. +
  3. at runtime, into pages that match URL patterns: using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. This is just like method (1), except you can add and remove content scripts at runtime.
  4. +
  5. at runtime, into specific tabs: using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a browser action.
  6. +
+ +

There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

+ +

Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a match pattern. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".

+ +

Ambiente de script de conteúdo

+ +

Acesso DOM

+ +

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

+ +

However, content scripts get a "clean view of the DOM". This means:

+ + + +

In Firefox, this behavior is called Xray vision.

+ +

For example, consider a web page like this:

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

The script "page-script.js" does this:

+ +
// page-script.js
+
+// add a new element to the DOM
+var p = document.createElement("p");
+p.textContent = "This paragraph was added by a page script.";
+p.setAttribute("id", "page-script-para");
+document.body.appendChild(p);
+
+// define a new property on the window
+window.foo = "This global variable was added by a page script";
+
+// redefine the built-in window.confirm() function
+window.confirm = function() {
+  alert("The page script has also redefined 'confirm'");
+}
+ +

Now an extension injects a content script into the page:

+ +
// content-script.js
+
+// can access and modify the DOM
+var pageScriptPara = document.getElementById("page-script-para");
+pageScriptPara.style.backgroundColor = "blue";
+
+// can't see page-script-added properties
+console.log(window.foo);  // undefined
+
+// sees the original form of redefined properties
+window.confirm("Are you sure?"); // calls the original window.confirm()
+ +

The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.

+ +

All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.

+ +

One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.

+ +

If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

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

Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See Sharing objects with page scripts for more details.

+ +

APIs da Extensão da Web

+ +

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

+ +

From extension:

+ + + +

From runtime:

+ + + +

From i18n:

+ + + +

From menus:

+ + + +

Everything from storage.

+ +

XHR e Fetch

+ +

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

+ +

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

+ +

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead. For cross-browser extensions their presence must be feature-detected.

+ +

Comunicar com scripts de segundo plano

+ +

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

+ +

There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.

+ +

One-off messages

+ +

To send one-off messages, with an optional response, you can use the following APIs:

+ + + + + + + + + + + + + + + + + + + + + +
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

For example, here's a content script which listens for click events in the web page. If the click was on a link, it messages the background page with the target URL:

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

The background script listens for these messages and displays a notification using the notifications API:

+ +
// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+  browser.notifications.create({
+    "type": "basic",
+    "iconUrl": browser.extension.getURL("link.png"),
+    "title": "You clicked a link!",
+    "message": message.url
+  });
+}
+
+ +

This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.

+ +

Connection-based messaging

+ +

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

+ +

Each side has a runtime.Port object, which they can use to exchange messages.

+ +

To create the connection:

+ + + +

Once each side has a port, the two sides can exchange messages using runtime.Port.postMessage() to send a message, and runtime.Port.onMessage to receive messages.

+ +

For example, as soon as it loads, this content script:

+ + + +
// content-script.js
+
+var myPort = browser.runtime.connect({name:"port-from-cs"});
+myPort.postMessage({greeting: "hello from content script"});
+
+myPort.onMessage.addListener(function(m) {
+  console.log("In content script, received message from background script: ");
+  console.log(m.greeting);
+});
+
+document.body.addEventListener("click", function() {
+  myPort.postMessage({greeting: "they clicked the page!"});
+});
+ +

The corresponding background script:

+ + + +
// background-script.js
+
+var portFromCS;
+
+function connected(p) {
+  portFromCS = p;
+  portFromCS.postMessage({greeting: "hi there content script!"});
+  portFromCS.onMessage.addListener(function(m) {
+    console.log("In background script, received message from content script")
+    console.log(m.greeting);
+  });
+}
+
+browser.runtime.onConnect.addListener(connected);
+
+browser.browserAction.onClicked.addListener(function() {
+  portFromCS.postMessage({greeting: "they clicked the button!"});
+});
+
+ +

Multiple content scripts

+ +

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

+ + + + + +
// background-script.js
+
+var ports = []
+
+function connected(p) {
+  ports[p.sender.tab.id]    = p
+  //...
+}
+
+browser.runtime.onConnect.addListener(connected)
+
+browser.browserAction.onClicked.addListener(function() {
+  ports.forEach(p => {
+        p.postMessage({greeting: "they clicked the button!"})
+    })
+});
+ + + + + +

Comunicar com a página da Web

+ +

Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

+ +

For example:

+ +
// page-script.js
+
+var messenger = document.getElementById("from-page-script");
+
+messenger.addEventListener("click", messageContentScript);
+
+function messageContentScript() {
+  window.postMessage({
+    direction: "from-page-script",
+    message: "Message from the page"
+  }, "*");
+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data &&
+      event.data.direction == "from-page-script") {
+    alert("Content script received message: \"" + event.data.message + "\"");
+  }
+});
+ +

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

+ +
+

Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.

+ +

To make a trivial example, suppose the content script code that receives the message does something like this:

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

Now the page script can run any code with all the privileges of the content script.

+
+ +

Using eval() in content scripts

+ +

In Chrome, eval() always runs code in the context of the content script, not in the context of the page.

+ +

In Firefox:

+ + + +

For example, consider a content script like this:

+ +
// content-script.js
+
+window.eval('window.x = 1;');
+eval('window.y = 2');
+
+console.log(`In content script, window.x: ${window.x}`);
+console.log(`In content script, window.y: ${window.y}`);
+
+window.postMessage({
+  message: "check"
+}, "*");
+ +

This code just creates some variables x and y using window.eval() and eval(), then logs their values, then messages the page.

+ +

On receiving the message, the page script logs the same variables:

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

In Chrome, this will produce output like this:

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

In Firefox the following output is produced:

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

The same applies to setTimeout(), setInterval(), and Function().

+ +

When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

+ +
// page.js redefines console.log
+
+var original = console.log;
+
+console.log = function() {
+  original(true);
+}
+
+ +
// content-script.js calls the redefined version
+
+window.eval('console.log(false)');
+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html deleted file mode 100644 index 1898b1712a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Conversão de uma extensão legada do Firefox -slug: Mozilla/Add-ons/WebExtensions/Conversao_de_uma_extensao_legada_do_firefox -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on ---- -
{{AddonSidebar}}
- -

Se desenvolveu uma extensão do Firefox utilziando XUL/XPCOM ou SDK de EXtras, esta página irá ajudá-lo a migraar a sua extensão para utilizar as APIs das Extensões da Web. O padrão para criar extensões para o Firefox é para utilizar as APIs das Extensões da Web. Este será a único tipo de extensão suportado no Firefox no fim de novembro de 2017, com o lançamento da versão 57 do Firefox.

- -

Início rápido

- -
    -
  1. Get an idea of the main things you'll have to change in your extension: - -
  2. -
  3. Rewrite your extension code. See below for migration paths for different types of extensions. From Firefox 51 onwards, you can embed an extension built using WebExtension APIs in a bootstrapped extension or an SDK add-on, and can thus port a legacy extension a piece at a time, and have a working extension at each step. See Embedded WebExtensions for more information.
  4. -
  5. When you're ready to submit the WebExtension version of your extension to AMO... wait a minute... are you truly ready? Because of the extensions permissions model, you cannot revert from WebExtensions back to using a legacy extension format. So test thoroughly, because this is a permanent one-way trip. Also, see the hybrid example below. If you're not ready, you can embed your WebExtension in a legacy extension container, which allows you to test your extension migration but still go back if needed in an emergency.
  6. -
  7. When you're really ready to submit the WebExtension version of your extension to AMO, first port your old add-on ID to the new WebExtension manifest.json file. Your extension must have the same ID as previous versions. Copy the value in the "id" field from your package.json file into the id field in the applications section of the WebExtension manifest.json file. Then you can submit your extension update to AMO as your normally would.
  8. -
- -
-

Note that this is a one-way conversion: You cannot update an extension using WebExtensions to use a legacy technology. This means that you must be sure that you are ready to commit to using WebExtension APIs before you submit the updated add-on to AMO.

-
- -

Camnihos de migração

- -

Extensões SDK

- -

Here is the comparison chart showing SDK APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtensions APIs, look below to learn how to request APIs and also how to implement them.

- -

Extensões XUL/XPCOM

- -

Here is the comparison chart showing XUL/XPCOM APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtension APIs, look below to learn how to request APIs and also how to implement them.

- -

Migração parcial

- -

An Embedded WebExtension is an extension that combines two types of extensions in one, by incorporating a WebExtension inside of a bootstrapped or SDK extension. If you have a legacy extension that writes data to the filesystem, and you’re planning to port it to WebExtensions, Embedded WebExtensions are available to help you transition. Embedded WebExtensions can be used to transfer the stored data of your add-on to a format that can be used by WebExtensions. This is essential because it lets you to convert your users without the need for them to take any actions.

- -

It’s important to emphasize that Embedded WebExtensions are intended to be a transition tool, and will not be supported past Firefox 57. They should not be used for add-ons that are not expected to transition to WebExtensions.

- -

Não vê as APIs das Extensões da Web que precisa?

- -

Develop WebExtension APIs for Firefox - If you're experienced with Mozilla infrastructure and would like to develop WebExtensions APIs directly for Firefox, here is a list of approved APIs that you can start contributing to.

- -

Experiment with new WebExtension APIs - If you want to prototype and tinker with WebExtensions APIs without having to build Firefox, WebExtensions Experiments is for you!

- -

Request a new WebExtensions API - If you want to request a new WebExtensions API, please read this page.

- -

Ferramentas

- - - -

Documentação

- - - -

Contactar

- - diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" deleted file mode 100644 index 8c0f5e3480..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" +++ /dev/null @@ -1,430 +0,0 @@ ---- -title: dubla padrões em extensão manifestos -slug: Mozilla/Add-ons/WebExtensions/dubla_padrões -translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns ---- -
{{AddonSidebar}}
- -

Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load content scripts into, and to specify which URLs to add webRequest listeners to.

- -

APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the content_scripts key in manifest.json.

- -

Match pattern structure

- -
-

Note: Some browsers don’t support certain schemes.
- Check the Browser compatibility table for details.

-
- -

All match patterns are specified as strings. Apart from the special <all_urls> pattern, match patterns consist of three parts: scheme, host, and path. The scheme and host are separated by ://.

- -
<scheme>://<host><path>
- -

scheme

- -

The scheme component may take one of two forms:

- - - - - - - - - - - - - - - - - - -
FormMatches
*Only "http" and "https" and in some browsers also "ws" and "wss".
One of http, https, ws, wss, ftp, ftps, data or file.Only the given scheme.
- -

host

- -

The host component may take one of three forms:

- - - - - - - - - - - - - - - - - - - - - - -
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
- -

host must not include a port number.

- -

host is optional only if the scheme is "file".

- -

Note that the wildcard may only appear at the start.

- -

path

- -

The path component must begin with a /.

- -

After that, it may subsequently contain any combination of the * wildcard and any of the characters that are allowed in URL paths or query strings. Unlike host, the path component may contain the * wildcard in the middle or at the end, and the * wildcard may appear more than once.

- -

The value for the path matches against the string which is the URL path plus the URL query string. This includes the ? between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with foo.bar, then you need to use an array of Match Patterns like ['*://*/*foo.bar', '*://*/*foo.bar?*']. The ?* is needed, rather than just bar*, in order to anchor the ending * as applying to the URL query string and not some portion of the URL path.

- -

Neither the URL fragment identifier, nor the # which precedes it, are considered as part of the path.

- -
-

Note: The path pattern string should not include a port number. Adding a port, as in: "http://localhost:1234/*" causes the match pattern to be ignored. However, "http://localhost:1234" will match with "http://localhost/*"

-
- -

<all_urls>

- -

The special value <all_urls> matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file".

- -

Examples

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternExample matchesExample non-matches
-

<all_urls>

- -

Match all URLs.

-
-

http://example.org/

- -

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

- -

ws://sockets.somewhere.org/

- -

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

- -

ftp://files.somewhere.org/

- -

ftps://files.somewhere.org/

-
-

resource://a/b/c/
- (unsupported scheme)

-
-

*://*/*

- -

Match all HTTP, HTTPS and WebSocket URLs.

-
-

http://example.org/

- -

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

- -

ws://sockets.somewhere.org/

- -

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

-
-

ftp://ftp.example.org/
- (unmatched scheme)

- -

ftps://ftp.example.org/
- (unmatched scheme)

- -

file:///a/
- (unmatched scheme)

-
-

*://*.mozilla.org/*

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains.

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

http://a.mozilla.org/

- -

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

- -

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

- -

ws://ws.mozilla.org/

- -

wss://secure.mozilla.org/something

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://mozilla.com/
- (unmatched host)

- -

http://firefox.org/
- (unmatched host)

-
-

*://mozilla.org/

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/".

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

ws://mozilla.org/

- -

wss://mozilla.org/

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://a.mozilla.org/
- (unmatched host)

- -

http://mozilla.org/a
- (unmatched path)

-
-

ftp://mozilla.org/

- -

Match only "ftp://mozilla.org/".

-
ftp://mozilla.org -

http://mozilla.org/
- (unmatched scheme)

- -

ftp://sub.mozilla.org/
- (unmatched host)

- -

ftp://mozilla.org/path
- (unmatched path)

-
-

https://*/path

- -

Match HTTPS URLs on any host, whose path is "path".

-
-

https://mozilla.org/path

- -

https://a.mozilla.org/path

- -

https://something.com/path

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.org/path/
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path?foo=1
- (unmatched path due to URL query string)

-
-

https://*/path/

- -

Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string.

-
-

https://mozilla.org/path/

- -

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

- -

https://something.com/path/

-
-

http://mozilla.org/path/
- (unmatched scheme)

- -

https://mozilla.org/path
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path/?foo=1
- (unmatched path due to URL query string)

-
-

https://mozilla.org/*

- -

Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string.

-
-

https://mozilla.org/

- -

https://mozilla.org/path

- -

https://mozilla.org/another

- -

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

- -

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

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.com/path
- (unmatched host)

-
-

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

- -

Match only this URL, or this URL with any URL fragment.

-
-

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

- -

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

-
Anything else.
-

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

- -

Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a /.

-
-

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

- -

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

- -

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

- -

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

- -

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

- -

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

-
-

https://mozilla.org/b/*/
- (unmatched path)

- -

https://mozilla.org/a/b/
- (unmatched path)

- -

https://mozilla.org/a/b/c/d/?foo=bar
- (unmatched path due to URL query string)

-
-

file:///blah/*

- -

Match any FILE URL whose path begins with "blah".

-
-

file:///blah/

- -

file:///blah/bleh

-
file:///bleh/
- (unmatched path)
- -

Invalid match patterns

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/"*" in host must be at the start.
https://*zilla.org/"*" in host must be the only character or be followed by ".".
http*://mozilla.org/"*" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be "*://*/*".
file://*Empty path: this should be "file:///*".
- -

Browser compatibility

- -

scheme

- - - -

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html b/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html deleted file mode 100644 index f16f7e619b..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: E a seguir? -slug: Mozilla/Add-ons/WebExtensions/E_a_seguir -tags: - - Extensão da Web - - Extensões - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/What_next_ ---- -
{{AddonSidebar}}
- -

Agora, irá estar pronto para começar a transformar a sua ideia de uma extensão de navegador em realidade. Antes de começar essa jornada, vale a pena estar ciente de algumas coisas que irão ajudar a facilitar.

- -

O seu ambiente de desenvolvimento

- -

You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things.

- -

If you use minification or obfuscation tools to deliver your final code, you’ll need to provide your source code to the AMO review process. Also, the tools you use—those for minification,  obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer’s computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools.

- -

Learn more about build tools

- -

Bibliotecas de terceiros

- -

Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way.

- -

Learn more about submitting source code

- -

O Acordo de Distribuição do Extra do Firefox

- -

Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience.

- -

Leia o acordo

- -

Learn more about signing

- -

O processo de revisão

- -

When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it’s passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it’s easy to check and avoid any likely review problems.

- -

Check out the review policy and guidelines

- -

Extensões do navegador em destaque no AMO

- -

If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser’s add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured.

- -

Saiba mais sobre como colocar os seus extras em destaque

- -

Continue a sua experiência de aprendizagem

- -

Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you’ll discover:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html new file mode 100644 index 0000000000..4a68068c6a --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html @@ -0,0 +1,28 @@ +--- +title: Exemplos de extensões +slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Examples +--- +
{{AddonSidebar}}
+ +

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório de exemplos de extensões simples em https://github.com/mdn/webextensions-examples. Este artigo descreve as APIs de Extensão da Web utilizadas nesse repositório.

+ +

Estes exemplos funcionam no Firefox Nightly: a maioria funciona nas versões anteriores do Firefox, mas verifique a chave strict_min_version em manifest.json da extensão para se certificar.

+ +

Se quiser experimentar estes exemplos, tem três opções principais:

+ +
    +
  1. Clone o repositório, depois carregue a extensão diretamente da sua diretoria fonte, utilizando a funcionalidade "Carregar Temporariamente os Extras". A extensão permanecerá carregada até que reinicie o Firefox.
  2. +
  3. Clone o repositório, depois utilize a ferramenta de linha de comando web-ext para executar o Firefox com a extensão instalada.
  4. +
  5. Clone o repositório, depois vá para a diretoria de build. Esta contém as versões criadas e assinadas de todos os exemplos, e assim pode abri-las no Firefox (utilizando Ficheiro/Abrir Ficheiro) e instale-as permanentemente, tal como uma extensão que instalaria a partir de addons.mozilla.org.
  6. +
+ +
+

Importante: Por favor, não submeta estes exemplos dos exemplos da 'Extensão da Web' para AMO (addons.mozilla.org), não precisa de assinar o extra para executar os exemplos da 'Extensão da Web'. Basta seguir os passos acima.

+
+ +

Se desejar contribuir para o repositório, envie-nos um pedido de submissão!

+ +

{{WebExtAllExamples}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html b/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html deleted file mode 100644 index 4a68068c6a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Exemplos de extensões -slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Examples ---- -
{{AddonSidebar}}
- -

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório de exemplos de extensões simples em https://github.com/mdn/webextensions-examples. Este artigo descreve as APIs de Extensão da Web utilizadas nesse repositório.

- -

Estes exemplos funcionam no Firefox Nightly: a maioria funciona nas versões anteriores do Firefox, mas verifique a chave strict_min_version em manifest.json da extensão para se certificar.

- -

Se quiser experimentar estes exemplos, tem três opções principais:

- -
    -
  1. Clone o repositório, depois carregue a extensão diretamente da sua diretoria fonte, utilizando a funcionalidade "Carregar Temporariamente os Extras". A extensão permanecerá carregada até que reinicie o Firefox.
  2. -
  3. Clone o repositório, depois utilize a ferramenta de linha de comando web-ext para executar o Firefox com a extensão instalada.
  4. -
  5. Clone o repositório, depois vá para a diretoria de build. Esta contém as versões criadas e assinadas de todos os exemplos, e assim pode abri-las no Firefox (utilizando Ficheiro/Abrir Ficheiro) e instale-as permanentemente, tal como uma extensão que instalaria a partir de addons.mozilla.org.
  6. -
- -
-

Importante: Por favor, não submeta estes exemplos dos exemplos da 'Extensão da Web' para AMO (addons.mozilla.org), não precisa de assinar o extra para executar os exemplos da 'Extensão da Web'. Basta seguir os passos acima.

-
- -

Se desejar contribuir para o repositório, envie-nos um pedido de submissão!

- -

{{WebExtAllExamples}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html b/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html new file mode 100644 index 0000000000..dc98e7fd37 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html @@ -0,0 +1,156 @@ +--- +title: Extensão das ferramentas de desenvolvimento +slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento +translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools +--- +
{{AddonSidebar}}
+ +
+

Esta página descreve as APIs das devtools  que existem no Firefox 55. Embora as APIs sejam baseadas nas APIs de devtools do Chrome, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

+
+ +

Pode utilizar as APIs das Extensões da Web para ampliar as ferramentas de desenvollvimento integradas no navegador. Para criar a extensão devtools, inclua a chave "devtools_page" no manifest.json:

+ +
"devtools_page": "devtools/devtools-page.html"
+ +

O valor desta chave é um URL a apontar para um ficheiro HTML que foi incorporado com a sua extensão. O URL deverá ser relativo ao próprio ficheiro manifest.json.

+ +

O ficheiro HTML define uma página especial na extensão, chamada de página devtools.

+ +

A página devtools

+ +

The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.

+ +

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

+ + + +

Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the runtime messaging APIs.

+ +

Criar painéis

+ +

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

+ +

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

+ +
browser.devtools.panels.create(
+  "My Panel",                      // title
+  "icons/star.png",                // icon
+  "devtools/panel/panel.html"      // content
+).then((newPanel) => {
+  newPanel.onShown.addListener(initialisePanel);
+  newPanel.onHidden.addListener(unInitialisePanel);
+});
+ +

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

+ +

Interagir com a janela de destino

+ +

The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the devtools.inspectedWindow API.

+ +

Executar código na janela de destino

+ +

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

+ +

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

+ + + +
+

Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.

+
+ +

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

+ +

Trabalhar com scripts de conteúdo

+ +

A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The devtools.inspectedWindow.tabId provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:

+ +
// devtools-panel.js
+
+const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
+
+window.addEventListener("click", () => {
+  browser.runtime.sendMessage({
+    tabId: browser.devtools.inspectedWindow.tabId,
+    script: scriptToAttach
+  });
+});
+ +
// background.js
+
+function handleMessage(request, sender, sendResponse) {
+  browser.tabs.executeScript(request.tabId, {
+    code: request.script
+  });
+}
+
+browser.runtime.onMessage.addListener(handleMessage);
+ +

If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

+ +

+ +

Limitações das APIs de devtools

+ +

These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.

+ +

devtools.inspectedWindow

+ +

The following are not supported:

+ + + +

None of the options to inspectedWindow.eval() are supported.

+ +

Scripts injected using inspectedWindow.eval() can't use any of the Console's command-line helper functions, like $0.

+ +

devtools.network

+ +

The following are not supported:

+ + + +

devtools.panels

+ +

O seguinte não é suportado:

+ + + +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html b/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html deleted file mode 100644 index a462a1c02d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Extensões e a Id. do extra -slug: Mozilla/Add-ons/WebExtensions/ExtennsoesWeb_e_a_id_do_extra -tags: - - Extensões da Web - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID ---- -
{{AddonSidebar}}
- -
-

Os extras do Firefox contêm uma Id. única que é utilziada para distinguir este extra de qualquer outro extra do Firefox.

- -

Este artigo descreve como as Ids. de extra são tratados para as extensões criadas com APIs WebExtensions.

-
- -

Firefox add-ons contain a unique identifier which is used both inside Firefox itself and on the addons.mozilla.org (AMO) website. For example, it's used by Firefox to check for updates to installed add-ons and to identify which objects (such as data stores) are controlled by this add-on.

- -

With older types of Firefox add-on, the add-on developer must set the add-on ID explicitly. XUL/XPCOM add-ons set the ID in the install manifest, while SDK add-ons set it in the package.json.

- -

However, from Firefox 48 you can develop, debug, publish, and update extensions without needing to set an explicit ID at all.

- -
-

Note that the ability to develop and debug WebExtensions that don't include an ID is new in Firefox 48. If you need to use an earlier version of Firefox, then you must use the applications key to set an ID explicitly.

-
- -

Basic workflow with no add-on ID

- -

Extensions can explicitly set the add-on ID using the applications key in manifest.json. However, this key is usually optional. If you don't set it, then you can usually develop, debug, publish, and update your extension without ever having to deal with an ID. One advantage of this is that Google Chrome does not recognize the applications key and will show a warning if you include it.

- -

Note, though, that some WebExtension APIs use the add-on ID and expect it to be the same from one browser session to the next. If you use these APIs in Firefox, then you must set the ID explicitly using the applications key. See When do you need an Add-on ID?.

- -

Developing and debugging

- -

Starting in Firefox 48, if your manifest.json does not contain an ID then the extension will be assigned a randomly-generated temporary ID when you install it in Firefox through about:debugging. If you then reload the extension using the "Reload" button, the same ID will be used. If you then restart Firefox and load the add-on again, it will get a new ID.

- -

If you turn the extension into an .xpi or .zip and install it through about:addons, it will not work. To have it work in this scenario, you will need to add in the applications key in manifest.json

- -

Publishing

- -

Once you have finished developing the extension, you can package it and submit it to AMO for review and signing. If the packaged extension you upload does not contain an ID, AMO will generate one for you. It's only at this point that the add-on will be assigned a permanent ID, which will be embedded in the signed packaged extension.

- -

Note that once an extension has been given a permanent ID, you can't then update it to use the Add-on SDK or legacy XUL/XPCOM techniques. If you do switch to one of these platforms, you must submit it as a distinct new add-on, with a new ID.

- -

Updating

- -

Even after this point, though, you don't generally have to deal with the ID at all. You can continue to develop the add-on without an ID, and when you want to update, upload the new version by visiting the add-on's AMO page. Because you are uploading the add-on through that page, AMO knows that this is an update to this particular add-on, even though it doesn't contain an ID.

- -
-

It's essential with this workflow that you update the add-on manually using its page on AMO, otherwise AMO will not understand that the submission is an update to an existing add-on, and will treat the update as a brand-new add-on.

-
- -

You can do the same thing if you are updating from an older add-on type, such as a XUL/XPCOM add-on, to use WebExtensions APIs. Just visit the old add-on's page on AMO, upload the new extension there, and it will be treated as an update to the old version.

- -

Quando é que precisa de uma Id. de extra?

- - - -

 

- -

 

- -

 

diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" deleted file mode 100644 index dc98e7fd37..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Extensão das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools ---- -
{{AddonSidebar}}
- -
-

Esta página descreve as APIs das devtools  que existem no Firefox 55. Embora as APIs sejam baseadas nas APIs de devtools do Chrome, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

Pode utilizar as APIs das Extensões da Web para ampliar as ferramentas de desenvollvimento integradas no navegador. Para criar a extensão devtools, inclua a chave "devtools_page" no manifest.json:

- -
"devtools_page": "devtools/devtools-page.html"
- -

O valor desta chave é um URL a apontar para um ficheiro HTML que foi incorporado com a sua extensão. O URL deverá ser relativo ao próprio ficheiro manifest.json.

- -

O ficheiro HTML define uma página especial na extensão, chamada de página devtools.

- -

A página devtools

- -

The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.

- -

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

- - - -

Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the runtime messaging APIs.

- -

Criar painéis

- -

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

- -

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

- -
browser.devtools.panels.create(
-  "My Panel",                      // title
-  "icons/star.png",                // icon
-  "devtools/panel/panel.html"      // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(initialisePanel);
-  newPanel.onHidden.addListener(unInitialisePanel);
-});
- -

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

- -

Interagir com a janela de destino

- -

The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the devtools.inspectedWindow API.

- -

Executar código na janela de destino

- -

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

- -

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

- - - -
-

Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.

-
- -

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

- -

Trabalhar com scripts de conteúdo

- -

A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The devtools.inspectedWindow.tabId provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:

- -
// devtools-panel.js
-
-const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
-
-window.addEventListener("click", () => {
-  browser.runtime.sendMessage({
-    tabId: browser.devtools.inspectedWindow.tabId,
-    script: scriptToAttach
-  });
-});
- -
// background.js
-
-function handleMessage(request, sender, sendResponse) {
-  browser.tabs.executeScript(request.tabId, {
-    code: request.script
-  });
-}
-
-browser.runtime.onMessage.addListener(handleMessage);
- -

If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

- -

- -

Limitações das APIs de devtools

- -

These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.

- -

devtools.inspectedWindow

- -

The following are not supported:

- - - -

None of the options to inspectedWindow.eval() are supported.

- -

Scripts injected using inspectedWindow.eval() can't use any of the Console's command-line helper functions, like $0.

- -

devtools.network

- -

The following are not supported:

- - - -

devtools.panels

- -

O seguinte não é suportado:

- - - -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html deleted file mode 100644 index 47730abceb..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Instalação temporária no Firefox -slug: Mozilla/Add-ons/WebExtensions/Instalacao_temporaria_no_Firefox -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox ---- -
{{AddonSidebar}}
- -

Este artigo descreve como um programador de extra (add-on) pode instalar temporariamente uma extensão no Firefox para testes e depuração. A extensão permanecerá instalada até que reinicie o Firefox. Pode utilizar este método com qualquer tipo de extensão sem reinício, incluindo as extensões bootstrapped e extras de Add-on SDK.

- -

Note that this is not how end users should install add-ons in Firefox. End users will install add-ons by downloading and opening packaged add-ons that have been signed by Mozilla. To learn how an extension developer can get an add-on packaged and signed, see Publishing your extension.

- -

To install an extension temporarily:

- - - -

The extension will be installed, and will stay installed until you restart Firefox.

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

Recarregar uma extensão temporária

- -

Starting in Firefox 48, there's a new button labeled "Reload" next to the extension's entry in about:debugging:

- -

This does what it says:

- - - -

{{EmbedYouTube("NuajE60jfGY")}}

- -
-

Note that in Firefox 48 only, "Reload" does not update the extension's name and description that are displayed in about:debugging and about:addons. This is fixed in Firefox 49.

-
- -

Utilizar a linha de comando

- -

If you are already using the command line for development, check out the web-ext tool. It automates the temporary installation step and automatically reloads your extension when its source code changes.

- -

Detetar instalaçao temporária

- -

Your extension can detect whether it was installed from about:debugging rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event, and check the value of details.temporary.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html b/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html new file mode 100644 index 0000000000..b938b514d4 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html @@ -0,0 +1,160 @@ +--- +title: Interceptar Pedidos HTTP +slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP +tags: + - Add-ons + - Como-fazer + - Extensões + - ExtensõesWeb +translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests +--- +
{{AddonSidebar}}
+ +

Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:

+ + + +

Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo webRequest:

+ + + +

Loggar pedidos URLs

+ +

Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:

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

De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:

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

Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

+ +

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

+ +

{{EmbedYouTube("X3rMgkRkB1Q")}}

+ +

Redirecting requests

+ +

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

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

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

+ +

Next, replace "background.js" with this:

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

Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the redirectUrl specified in the function.

+ +

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.

+ +

Also note that we're passing an option called "blocking": we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on "blocking".

+ +

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

+ +

{{EmbedYouTube("ix5RrXGr0wA")}}

+ +

Modifying request headers

+ +

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

+ +

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

+ +

Replace "background.js" with code like this:

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

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Learn more

+ +

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html deleted file mode 100644 index b938b514d4..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: Interceptar Pedidos HTTP -slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP -tags: - - Add-ons - - Como-fazer - - Extensões - - ExtensõesWeb -translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests ---- -
{{AddonSidebar}}
- -

Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:

- - - -

Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo webRequest:

- - - -

Loggar pedidos URLs

- -

Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:

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

De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:

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

Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

- -

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

- -

{{EmbedYouTube("X3rMgkRkB1Q")}}

- -

Redirecting requests

- -

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

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

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

- -

Next, replace "background.js" with this:

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

Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the redirectUrl specified in the function.

- -

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.

- -

Also note that we're passing an option called "blocking": we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on "blocking".

- -

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

- -

{{EmbedYouTube("ix5RrXGr0wA")}}

- -

Modifying request headers

- -

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

- -

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

- -

Replace "background.js" with code like this:

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

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

- -

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

- -

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

- -

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

- -

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

- -

Learn more

- -

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html deleted file mode 100644 index 7093d3355c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Botão da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação da página, esta opção da inteface do utilizador é um botão adicionado à barra de endereço do navegador. Os utilziadores clicam no botão para interagir com a sua extensão.

- -

- -

Use this button when a feature is only relevant for some web pages. By default, the address bar button is hidden in all browser tabs, and you call pageAction.show() and pageAction.hide() to show or hide it in specific tabs.

- -

Compare to the toolbar button, which offers similar behavior but is used in situations where the extension's features are applicable to almost every web page.

- -

Especificar a ação da página

- -

You define the page action's properties using the page_action key in manifest.json:

- -
"page_action": {
-  "browser_style": true,
-  "default_icon": {
-    "19": "button/geo-19.png",
-    "38": "button/geo-38.png"
-  },
-  "default_title": "Whereami?"
-}
- -

The only mandatory key is default_icon.

- -

There are two ways to specify a page action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using pageAction.onClicked:

- -
browser.pageAction.onClicked.addListener(handleClick);
- -

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have one page action only.

- -

You can change any of the page action properties programmatically using the pageAction API.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use page action:

- - diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" deleted file mode 100644 index c5da78003b..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Botão da Barra de Ferramentas -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador -tags: - - Extensão da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação do navegador, esta opção da interface do utilizador é um botão adicionado à barra de ferramentas do navegador. Os utilizadores clicam no botão para interagir com a sua extensão.
-

- -

The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see Page actions and browser actions.

- -

Especificar a ação do navegador

- -

Define as propriedades da ação do navegador utilizando a chave browser_action em manifest.json:

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

The only mandatory key is default_icon.

- -

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

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

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have only one browser action.

- -

You can change any of the browser action properties programmatically using the browserAction API.

- -

Ícones

- -

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html deleted file mode 100644 index 2cfa1800a7..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Barras laterais -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars ---- -
{{AddonSidebar}}
- -
-

 

- -

Uma barra lateral é um painel que é exibido no lado esquerdo da janela do navegador, ao lado da página da Web. O navegador fornece uma IU que permite ao utilizador ver as barras laterais atualmente disponíveis e selecionar uma barra lateral para exibir. Por exemplo, o Firefox tem um menu 'Ver -> Barra lateral'. Apenas pode ser exibida uma barra lateral de cada vez, e essa barra lateral será exibida para todos os separadores e todas as janelas do navegador.

- -

O navegador poderá incluir uma série de barras laterais integradas. Por exemplo, o Firefox inclui uma barra lateral para interagir com marcadores:

- -

Using the sidebar_action manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars.

- -

Like a browser action popup, you specify the sidebar's contents as an HTML document. When the user opens the sidebar, its document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well.

- -

You can set a document for a particular tab using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API:

- -
// sidebar.js
-browser.windows.getCurrent({populate: true}).then((windowInfo) => {
-  myWindowId = windowInfo.id;
-});
- -

This is useful if a sidebar wants to display different content for different windows. For an example of this, see the "annotate-page" example.

- -

Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

- -

Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages.

- -

When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for extension to open sidebars programmatically: sidebars can only be opened by the user.

- -

Especificar barras laterais

- -

To specify a sidebar, define the default document with the sidebar_action manifest.json key, alongside a default title and icon:

- -
"sidebar_action": {
-  "default_title": "My sidebar",
-  "default_panel": "sidebar.html",
-  "default_icon": "sidebar_icon.png"
-}
- -

You can change the title, panel, and icon programmatically using the {{WebExtAPIRef("sidebarAction")}} API.

- -

Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox.

- -

Exemplo

- -

O repositório de exemplos das extensões da Web no GitHub, contém vários exemplos de extensões que utilizam a barra lateral:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html deleted file mode 100644 index a2bc9921ad..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Painéis das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels -tags: - - Extensões da Web - - Guía - - Interface do Utilizador - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels ---- -
{{AddonSidebar}}
- -
-

Esta funcionalidade está disponível desde o Firefox 54.

-
- -

Quando uma extensão fornece ferramentas que são úteis para os programadores, é possível adicionar uma IU para as mesmas para as ferramentas de desenvolvimento do navegador como um novo painel.

- -

Simple example showing the addition of "My panel" to the Developer Tools tabs.

- -

Especificar um painel de ferramentas de desenvolvimento

- -

Um painél das ferramentas de desenvovlimento é adicionado utilizando a API devtools.panels, que precisa de ser executada a partir de uma página de devtools especial.

- -

Adicione a páginas de devtools, incluindo a chave devtools_page na extensão de manifest.json e forneça a localização do ficheiro HTML da página na extensão:

- -
"devtools_page": "devtools-page.html"
- -

From the devtools page, call a script that will add the devtools panel:

- -
<body>
-  <script src="devtools.js"></script>
-</body>
- -

In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:

- -
function handleShown() {
-  console.log("panel is being shown");
-}
-
-function handleHidden() {
-  console.log("panel is being hidden");
-}
-
-browser.devtools.panels.create(
-  "My Panel",           // title
-  "icons/star.png",           // icon
-  "devtools/panel/panel.html"          // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(handleShown);
-  newPanel.onHidden.addListener(handleHidden);
-});
- -

The extension can now run code in the inspected window using devtools.inspectedWindow.eval() or by injecting a content script via the background script by passing a message. You can find more details on how to do this in Extending the developer tools.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html deleted file mode 100644 index bc2f1bd2da..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html +++ /dev/null @@ -1,453 +0,0 @@ ---- -title: Estilos de navegador -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles ---- -
{{AddonSidebar}}
- -

Certain user interface components - browser and page action popups, sidebars, and options pages - are specified by your extension in essentially the same way:

- -
    -
  1. create an HTML file defining the structure of the UI element
  2. -
  3. add a manifest.json key (browser_action, page_action, sidebar_action, or options_ui) pointing to that HTML file.
  4. -
- -

One of the challenges with this approach is styling the element in such a way that it fits in with the browser's own style. To help with this, the manifest.json keys include an extra optional property: browser_style. If this is included and set to true, then your document will get one or more extra stylesheets that will help make it look consistent with the browser's UI and with other extensions that use the browser_style property.

- -

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css. The extra stylesheet at chrome://browser/content/extension-mac.css is also included on OS X.

- -

Most styles are automatically applied, but some elements require you to add the non-​standard browser-style class to get their styling since Firefox 55, as detailed in the table below:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
<button> -
-<button class="browser-style">Click me</button>{{non-standard_inline}}
-
-

<select>

-
-
-<select class="browser-style" name="select">
-  <option value="value1">Value 1</option>
-  <option value="value2" selected>Value 2</option>
-  <option value="value3">Value 3</option>
-</select>
-
<textarea> -
-<textarea class="browser-style">Write here</textarea>
-
Parent of an <input> -
-<div class="browser-style">
-  <input type="radio" id="op1" name="choices" value="op1">
-  <label for="op1">Option 1</label>
-
-  <input type="radio" id="op2" name="choices" value="op2">
-  <label for="op2">Option 2</label>
-</div>
-
- -

Compatibilidade de navegador

- - - -

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

- -

Componentes de Painel do Firefox

- -
-

{{NonStandardBadge(1)}} Non-Standard
- This feature is non-standard and only works in Firefox.

-
- -

The chrome://browser/content/extension.css stylesheet also contains the styles for the Firefox Panel Components.

- -

The legacy Firefox Style Guide documents proper usage.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
Cabeçalho -
-<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><img src="image.svg"/></div>
-  <div class="text-section-header">Header</div>
-</header>
-
Rodapé -
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
-
Separadores -
-<div class="panel-section panel-section-tabs">
-  <button class="panel-section-tabs-button selected">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-</div>
-
Form -
-<div class="panel-section panel-section-formElements">
-  <div class="panel-formElements-item">
-    <label for="name01">Label:</label>
-    <input type="text" value="Name" id="name01" />
-  </div>
-  <div class="panel-formElements-item">
-    <label for="picker01">Label:</label>
-    <select id="picker01">
-      <option value="value1" selected="true">Dropdown</option>
-      <option value="value2">List Item</option>
-      <option value="value3">List Item</option>
-    </select>
-  </div>
-  <div class="panel-formElements-item">
-    <label for="placeholder01">Label:</label>
-    <input type="text" placeholder="Placeholder" id="placeholder01" />
-    <button name="expander" class="expander"></button>
-  </div>
-</div>
-
Menu -
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
- -

Exemplo

- -

HTML

- -
<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><!-- An image goes here. --></div>
-  <div class="text-section-header">Header</div>
-</header>
-
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
- - - -

Result

- -

{{EmbedLiveSample("Example","640","360")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html deleted file mode 100644 index 6ec29a7fcf..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Interface do utilizador -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador -tags: - - Interface do Utilizador - - Landing - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/user_interface ---- -
{{AddonSidebar}}
- -

As extensões que utilizam as APIs de WebExtension são fornecidas com várias opções de interface do utilizador, e assim, as suas funcionalidades podem ficar disponíveis para o utilizador. Um resumo dessas opções é fornecido abaixo, com uma introdução mais detalhada para cada opção da interface do utilziador nesta secção .

- -
-

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Opção de UIDescriçãoExemplo
Browser toolbar buttonA button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example of a WebExtension toolbar button
Browser toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a WebExtension toolbar button with a popup
Address bar buttonA button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemsMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.
Sidebar -

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

-
Example of a WebExtension's sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page in the from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Bundled web pagesUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationsTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example notification from a WebExtension
Address bar suggestionsOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelsA tab with an associated HTML document that displays in the browser's developer tools.New panel tab in the Developer Tools tab bar
- -

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html deleted file mode 100644 index 231a800bc3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Itens do menu de contexto -slug: >- - Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items ---- -
{{AddonSidebar}}
- -
-

Essa opção da interface do utilizador adiciona um ou mais itens a um menu de contexto do navegador.

- -

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

- -

You would use this option to expose features that are relevant to specific browser or web page contexts. For example, you could show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("contextMenus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("contextMenus.remove")}}.

- -

Especificar itens do menu de contexto

- -

You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the contextMenus permission in your manifest.json to be able to take advantage of the API.

- -
"permissions": ["contextMenus"]
- -

You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:

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

Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.

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

Exemplos

- -

O repositório de wexemplos das Extensões da Web no GitHub, contém vários exemplos de extensões que utilizam os itens do menu de contexto:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html deleted file mode 100644 index 5b38d4f29f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Notificações -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications ---- -
{{AddonSidebar}}
- -
-

As notificações permitem-lhe comunicar a informação sobre a sua extensão ou o seu conteúdo utilizando o serviço de notificação do sistema operativo subjacente:

- -

- -

As notificações podem incluir uma chamada para ação para o utilizador, e o seu extra pode escutar o utilizador a clicar na notificação ou a notificação a fechar.

- -

Especificar as notificações

- -

Pode gerir as notificações programaticamente, utilizando a API {{WebExtAPIRef("notifications")}}. Para utilizar esta API deve solicitar a permissão de notifications no seu manifest.json:

- -
"permissions": ["notifications"]
- -

Depois, pode utilziar {{WebExtAPIRef("notifications.create")}} para criar as suas notificações, como neste exemplo de notify-link-clicks-i18n:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
-browser.notifications.create({
-  "type": "basic",
-  "iconUrl": browser.extension.getURL("icons/link-48.png"),
-  "title": title,
-  "message": content
-});
- -

Este código cria uma notificação com um ícone, título, e mensagem.

- -

Se a notificação incluir uma chamada para ação, pode escutar o utilizador a clicar na notificação para chamar a ação para manipular a ação:

- -
browser.notifications.onClicked.addListener(handleClick);
-
- -

Se estiver a enviar chamadas para ação através das notificações, também irá querer definir a notificação opcional id, e assim, pode saber qual a chamada para ação que o utilizador selecionou.

- -

Exemplos

- -

O repositório dos exemplos da extensões da Web no GitHub, contém vários exemplos das extensões que utilizam creates notifications:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html deleted file mode 100644 index c0f9f41dca..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Sugestões da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox ---- -
{{AddonSidebar()}}
- -

Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples.

- -

Especificando a personalização de omnibox

- -

You tell your extension that it is going to customize the address bar suggestions by including the omnibox key and definition of the trigger keyword in its manifest.json file:

- -
  "omnibox": { "keyword" : "cs" }
- -

In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature:

- -
browser.omnibox.setDefaultSuggestion({
-  description: `Search the firefox codebase
-    (e.g. "hello world" | "path:omnibox.js onInputChanged")`
-});
- -

You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a search of https://searchfox.org/mozilla-central using the term entered by the user:

- -
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
-  let headers = new Headers({"Accept": "application/json"});
-  let init = {method: 'GET', headers};
-  let url = buildSearchURL(text);
-  let request = new Request(url, init);
-
-  fetch(request)
-    .then(createSuggestionsFromResponse)
-    .then(addSuggestions);
-});
- -

If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down.

- -

The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened:

- -
browser.omnibox.onInputEntered.addListener((text, disposition) => {
-  let url = text;
-  if (!text.startsWith(SOURCE_URL)) {
-    // Update the url if the user clicks on the default suggestion.
-    url = `${SEARCH_URL}?q=${text}`;
-  }
-  switch (disposition) {
-    case "currentTab":
-      browser.tabs.update({url});
-      break;
-    case "newForegroundTab":
-      browser.tabs.create({url});
-      break;
-    case "newBackgroundTab":
-      browser.tabs.create({url, active: false});
-      break;
-  }
-});
- -

 

- -

Exemplos

- -

O repositório dos exemplos das extensões da Web no GitHub inclui o exemplo firefox-code-search que personaliza a barra de pesquisa.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html deleted file mode 100644 index b3bee11990..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Página de opções -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages ---- -
{{AddonSidebar}}
- -
-

Uma página de Opções permite-lhe definir as preferências para sua extensão que os seus utilizadores podem alterar. Os utilizadores podem aceder á página das opções para uma extensão a partir do do gestor de extras do navegador:

- -

{{EmbedYouTube("02oXAcbUv-s")}}

- -

The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another.

- - - -

You can open the page programmatically by calling runtime.openOptionsPage().

- -

Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details.

- -

Especificar a página de opções

- -

To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the favourite-colour example, includes a JavaScript file:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-  </head>
-
-<body>
-  <form>
-      <label>Favourite colour</label>
-      <input type="text" id="colour" >
-      <button type="submit">Save</button>
-  </form>
-  <script src="options.js"></script>
-</body>
-
-</html>
- -

JavaScript em execução na página pode utilizar a API das Extensões da Web que o extra tem permissões para. Em particular, pode utilziar a APi de armazenamento para manter as preferências.

- -

Package the page's files in your extension.

- -

You also need to include the options_ui key in your manifest.json file, giving it the URL to the page.

- -
"options_ui": {
-  "page": "options.html",
-  "browser_style": true
-},
- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use an options page:

- - -
diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" deleted file mode 100644 index 4bf94b9653..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Páginas de extensão -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages ---- -
{{AddonSidebar()}}
- -

Pode inclur páginas html na sua extensão para fornecer formulários, ajuda, ou qualquer outro conteúdo que a sua extensão precisar.

- -

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

- -

These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts.

- -

Especificar páginas de extensão

- -

You can include HTML files, and their associated CSS or JavaScript files, in your extension. The files can be included in the root or organized within meaningful sub-folders.

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

Exibir páginas de extensão

- -

There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}.

- -

Using windows.create(), for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience:

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

When the window is no longer needed, it can be closed programmatically, for example, after the user clicks a button, by passing the id of the current window to {{WebExtAPIRef("windows.remove()")}}:

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

Páginas de extensão e histório

- -

By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record:

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

To use the history API, you must request the "history" permission in your manifest.json file.

- -

Desenho da página da Web

- -

For details on how to design your web page's to match the style of Firefox, see the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub includes the window-manipulator example, which implements several of the options for creating windows.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html deleted file mode 100644 index 6bbf3f7ce8..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Janelas (Popups) -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups -tags: - - Extensions - - IU - - Interface do Utilizador - - Janela - - popup -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups ---- -
{{AddonSidebar}}
- -
-

Uma janela (popup) é uma janela que está associada com um botão da barra de ferramentas ou botão da barra de endereço.

- -

- -

Quando o usuário clica no botão, a janela popup é exibida. Quando o usuário clica em qualquer lugar fora do popup, ele é fechado. O popup pode ser fechado via programação usando a função window.close() em um script sendo executado no popup. Entretanto, você não pode abrir o popup via programação a partir do código JavaScript da extensão: ele somente se abre em resposta a uma ação do usuário.

- -

Você pode definir um atalho de teclado que abre o popup usando "_execute_browser_action" and "_execute_page_action". Veja a documentação da chave commands       no manifest.json.

- -

Especificar uma janela

- -

O popup é definido por um arquivo HTML, que pode incluir arquivos CSS e JavaScript, como uma página comum. Diferentemente de uma página comum, o código JavaScript pode usar todos os WebExtension APIs que a extensão tem permissions .

- -

O documento do popup é carregado toda vez que ele é exibido, e descarregado quando o popup é fechado.

- -

O arquivo HTML é incluído na extensão e especificado como parte do  browser_action ou chave page_action por "default_popup" no arquivo manifest.json:

- -
  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  }
- -

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

- -

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

- -

Depurar janelas

- -

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

- -

Redimensionar janelas

- -

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

- -

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

- -

No Firefox Android 57, popup é mostrada como uma página normal num novo separador.

- -

Desenho de janela

- -

Para obter detalhes sobre como desenhar a sua janela (popup) da página da Web para combinar com o estilo do Firefox, consulte a documentação Photon Design System.

- -

Exemplos

- -

The webextensions-examples  repository on GitHub includes the beastify example which implements a browser action with a popup.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html deleted file mode 100644 index c9fd687771..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Ícones (icons) -slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObjeto
ObrigatórioNão
Exemplo -
-"icons": {
-  "48": "icon.png",
-  "96": "icon@2x.png"
-}
-
- -

The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.

- -

It consists of key-value pairs of image size in px and image path relative to the root directory of the extension.

- -

If icons is not supplied, a standard extension icon will be used by default.

- -

You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components.

- -

Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons.

- -

Exemplo

- -

The keys in the icons object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays.

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

SVG

- -

You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though:

- -
    -
  1. You need to specify a viewBox in the image. E.g.: -
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    -
  2. -
  3. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: -
    "icons": {
    -  "48": "icon.svg",
    -  "96": "icon.svg"
    -}
    -
  4. -
- -
-

If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon.

-
- -

Compatibilidade de navegador

- - - -

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html new file mode 100644 index 0000000000..c9fd687771 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html @@ -0,0 +1,78 @@ +--- +title: Ícones (icons) +slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones +tags: + - Extensões + - Extensões da Web + - Extras +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
TipoObjeto
ObrigatórioNão
Exemplo +
+"icons": {
+  "48": "icon.png",
+  "96": "icon@2x.png"
+}
+
+ +

The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.

+ +

It consists of key-value pairs of image size in px and image path relative to the root directory of the extension.

+ +

If icons is not supplied, a standard extension icon will be used by default.

+ +

You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components.

+ +

Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons.

+ +

Exemplo

+ +

The keys in the icons object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays.

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

SVG

+ +

You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though:

+ +
    +
  1. You need to specify a viewBox in the image. E.g.: +
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    +
  2. +
  3. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: +
    "icons": {
    +  "48": "icon.svg",
    +  "96": "icon.svg"
    +}
    +
  4. +
+ +
+

If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon.

+
+ +

Compatibilidade de navegador

+ + + +

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html b/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html new file mode 100644 index 0000000000..8c0f5e3480 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html @@ -0,0 +1,430 @@ +--- +title: dubla padrões em extensão manifestos +slug: Mozilla/Add-ons/WebExtensions/dubla_padrões +translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns +--- +
{{AddonSidebar}}
+ +

Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load content scripts into, and to specify which URLs to add webRequest listeners to.

+ +

APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the content_scripts key in manifest.json.

+ +

Match pattern structure

+ +
+

Note: Some browsers don’t support certain schemes.
+ Check the Browser compatibility table for details.

+
+ +

All match patterns are specified as strings. Apart from the special <all_urls> pattern, match patterns consist of three parts: scheme, host, and path. The scheme and host are separated by ://.

+ +
<scheme>://<host><path>
+ +

scheme

+ +

The scheme component may take one of two forms:

+ + + + + + + + + + + + + + + + + + +
FormMatches
*Only "http" and "https" and in some browsers also "ws" and "wss".
One of http, https, ws, wss, ftp, ftps, data or file.Only the given scheme.
+ +

host

+ +

The host component may take one of three forms:

+ + + + + + + + + + + + + + + + + + + + + + +
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
+ +

host must not include a port number.

+ +

host is optional only if the scheme is "file".

+ +

Note that the wildcard may only appear at the start.

+ +

path

+ +

The path component must begin with a /.

+ +

After that, it may subsequently contain any combination of the * wildcard and any of the characters that are allowed in URL paths or query strings. Unlike host, the path component may contain the * wildcard in the middle or at the end, and the * wildcard may appear more than once.

+ +

The value for the path matches against the string which is the URL path plus the URL query string. This includes the ? between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with foo.bar, then you need to use an array of Match Patterns like ['*://*/*foo.bar', '*://*/*foo.bar?*']. The ?* is needed, rather than just bar*, in order to anchor the ending * as applying to the URL query string and not some portion of the URL path.

+ +

Neither the URL fragment identifier, nor the # which precedes it, are considered as part of the path.

+ +
+

Note: The path pattern string should not include a port number. Adding a port, as in: "http://localhost:1234/*" causes the match pattern to be ignored. However, "http://localhost:1234" will match with "http://localhost/*"

+
+ +

<all_urls>

+ +

The special value <all_urls> matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file".

+ +

Examples

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternExample matchesExample non-matches
+

<all_urls>

+ +

Match all URLs.

+
+

http://example.org/

+ +

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

+ +

ws://sockets.somewhere.org/

+ +

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

+ +

ftp://files.somewhere.org/

+ +

ftps://files.somewhere.org/

+
+

resource://a/b/c/
+ (unsupported scheme)

+
+

*://*/*

+ +

Match all HTTP, HTTPS and WebSocket URLs.

+
+

http://example.org/

+ +

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

+ +

ws://sockets.somewhere.org/

+ +

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

+
+

ftp://ftp.example.org/
+ (unmatched scheme)

+ +

ftps://ftp.example.org/
+ (unmatched scheme)

+ +

file:///a/
+ (unmatched scheme)

+
+

*://*.mozilla.org/*

+ +

Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains.

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

http://a.mozilla.org/

+ +

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

+ +

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

+ +

ws://ws.mozilla.org/

+ +

wss://secure.mozilla.org/something

+
+

ftp://mozilla.org/
+ (unmatched scheme)

+ +

http://mozilla.com/
+ (unmatched host)

+ +

http://firefox.org/
+ (unmatched host)

+
+

*://mozilla.org/

+ +

Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/".

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

ws://mozilla.org/

+ +

wss://mozilla.org/

+
+

ftp://mozilla.org/
+ (unmatched scheme)

+ +

http://a.mozilla.org/
+ (unmatched host)

+ +

http://mozilla.org/a
+ (unmatched path)

+
+

ftp://mozilla.org/

+ +

Match only "ftp://mozilla.org/".

+
ftp://mozilla.org +

http://mozilla.org/
+ (unmatched scheme)

+ +

ftp://sub.mozilla.org/
+ (unmatched host)

+ +

ftp://mozilla.org/path
+ (unmatched path)

+
+

https://*/path

+ +

Match HTTPS URLs on any host, whose path is "path".

+
+

https://mozilla.org/path

+ +

https://a.mozilla.org/path

+ +

https://something.com/path

+
+

http://mozilla.org/path
+ (unmatched scheme)

+ +

https://mozilla.org/path/
+ (unmatched path)

+ +

https://mozilla.org/a
+ (unmatched path)

+ +

https://mozilla.org/
+ (unmatched path)

+ +

https://mozilla.org/path?foo=1
+ (unmatched path due to URL query string)

+
+

https://*/path/

+ +

Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string.

+
+

https://mozilla.org/path/

+ +

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

+ +

https://something.com/path/

+
+

http://mozilla.org/path/
+ (unmatched scheme)

+ +

https://mozilla.org/path
+ (unmatched path)

+ +

https://mozilla.org/a
+ (unmatched path)

+ +

https://mozilla.org/
+ (unmatched path)

+ +

https://mozilla.org/path/?foo=1
+ (unmatched path due to URL query string)

+
+

https://mozilla.org/*

+ +

Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string.

+
+

https://mozilla.org/

+ +

https://mozilla.org/path

+ +

https://mozilla.org/another

+ +

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

+ +

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

+
+

http://mozilla.org/path
+ (unmatched scheme)

+ +

https://mozilla.com/path
+ (unmatched host)

+
+

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

+ +

Match only this URL, or this URL with any URL fragment.

+
+

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

+ +

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

+
Anything else.
+

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

+ +

Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a /.

+
+

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+
+

https://mozilla.org/b/*/
+ (unmatched path)

+ +

https://mozilla.org/a/b/
+ (unmatched path)

+ +

https://mozilla.org/a/b/c/d/?foo=bar
+ (unmatched path due to URL query string)

+
+

file:///blah/*

+ +

Match any FILE URL whose path begins with "blah".

+
+

file:///blah/

+ +

file:///blah/bleh

+
file:///bleh/
+ (unmatched path)
+ +

Invalid match patterns

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/"*" in host must be at the start.
https://*zilla.org/"*" in host must be the only character or be followed by ".".
http*://mozilla.org/"*" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be "*://*/*".
file://*Empty path: this should be "file:///*".
+ +

Browser compatibility

+ +

scheme

+ + + +

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html deleted file mode 100644 index c2d7ef5d71..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: O que são extensões? -slug: Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions -tags: - - Extensões - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions ---- -
{{AddonSidebar}}
- -

Uma extensão adiciona funcionalidades e funções a um navegador. É criada, utilizando a tecnologia padrão baseada na Web - CSS, HTML e JavaScript. Esta tira vantagem de algumas APIs da Web, como JavaScript pode em uma página da web, mas uma extensão também tem acesso ao seu próprio conjunto de APIs de JavaScript. Isto significa que pode fazer muito mais numa extensão do que pode com o código numa página da Web. Aqui estão apenas alguns exemplos das coisas que pode fazer.

- -

Melhore ou complemente um site da Web: utilize um extra para fornecer funcionalidades adicionais no navegador ou informação do seu site da Web. Permita que os utilizadores recolham detalhes das páginas que eles visitam, para melhorar o serviço que oferece.

- -

- -

Exemplos: Amazon Assistant para Firefox, OneNote Web Clipper, e Grammarly for Firefox

- -

Deixe que os utilizadores mostrem a sua personalidade: Browser extensions can manipulate the content of pages browsed by a user. Help the user add a favorite logo or picture as the background to every page they visit. Extensions also give you the ability to update the look of the Firefox UI. (Update the Firefox UI using standalone theme add-ons too).

- -

- -

Exemplos: MyWeb New Tab, Tabliss, e VivaldiFox

- -

Adicionar ou remover conteúdo das páginas da Web: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page’s HTML and CSS, you can help users see the web the way they want to.

- -

- -

Exemplos: uBlock Origin, Reader, e Toolbox para Google Play Store™

- -

Adicionar ferramentas e novas funcionalidades de navegação: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website’s features or functionality, it doesn't have to be your website.

- -

- -

Examples: QR Code Image Generator, Swimlanes for Trello, and Tomato Clock

- -

Jogos: Offer traditional computer games, with off-line play features, but also explore new game possibilities, for example, by incorporating gameplay into everyday browsing.

- -

 

- -

Examples: Asteroids in Popup, Solitaire Card Game New Tab, and 2048 Prime.

- -

Adicionar ferramentas de desenvolvimento: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar.

- -

- -

Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools

- -

Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.

- -

If you have ideas or questions, or need help migrating a legacy add-on to WebExtensions APIs, you can reach us on the dev-addons mailing list or in #extdev on IRC.

- -

E a seguir?

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html b/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html deleted file mode 100644 index a6eb21ffc1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html +++ /dev/null @@ -1,304 +0,0 @@ ---- -title: Primeiros passos com web-ext -slug: Mozilla/Add-ons/WebExtensions/Primeiros_passos_com_web-ext -tags: - - Extensão da Web - - Ferramentas - - Guía - - Instalação - - Testes - - empacotamento - - web-ext -translation_of: Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext ---- -
{{AddonSidebar}}
- -

web-ext é uma ferramenta da linha de comando desenhada para acelerar várias partes do processo de desenvolvimento da extensão, tornado o desenvolvimento mais rápido e fácil. Este artigo explica como instalar e utilizar web-ext.

- -

Instalação

- -

web-ext is a node-based application that you install with the nodejs/npm tool. Install web-ext using the following command:

- -
npm install --global web-ext
- -

web-ext requires the current LTS (long-term support) version of NodeJS.

- -

To test whether the installation worked run the following command, which displays the web-ext version number:

- -
web-ext --version
- -

Utilizar web-ext

- -

Before you start using web-ext, locate an example extension to use—if you don't have one, use one from the webextensions-examples repo.

- -

Testar uma extensão

- -

Test an extension in Firefox by cd'ing into your extension's root directory and entering:

- -
web-ext run
- -

This starts Firefox and loads the extension temporarily in the browser, just as you can on the about:debugging page.

- -

See the run reference guide to learn more.

- -

Recarregamento automático da extensão

- -

The run command watches your source files and tells Firefox to reload the extension after you edit and save a file. For example, if you changed the name property in your manifest.json file, Firefox displays the new name. This makes it easy to try out new features because you can see the effect immediately. The automatic reloading feature is active by default, you use it like this:

- -
web-ext run
- -

You can also press the r key in the web-ext terminal to trigger an extension reload.

- -

If you experience unexpected behavior with the reloading feature, please file a bug. You can also disable reloading like this:

- -
web-ext run --no-reload
- -
-

O reccaregamento da extensão só é suportado a paratir da versão do Firefox 49 ou superior .

-
- -

Testar em versões diferentes do Firefox

- -

To run your extension in a version of Firefox Desktop other than the default, use the --firefox option to specify a full path to the binary file. Here is an example for Mac OS:

- -
web-ext run --firefox=/Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
- -

On Windows, the path needs to include firefox.exe, for example:

- -
web-ext run --firefox="C:\Program Files\Mozilla Firefox\firefox.exe"
- -

See the run command reference to learn more.

- -

Testar no Firefox 48

- -

Firefox 48 was the first stable version to use the WebExtension platform, but it doesn't allow web-ext to install an extension remotely. You need to run your extension in Firefox 48 using:

- -
web-ext run --pre-install
- -

Testar no Firefox para Android

- -

To run your extension in Firefox for Android, follow these instructions to set up your computer and device.

- -

With your device connected to your development computer, run:

- -
web-ext run --target=firefox-android
- -

This command displays the device ID for your connected Android device or devices. If you don't see a list of device IDs, make sure you set up the device for development correctly.

- -

Now, add the device ID to the command:

- -
web-ext run --target=firefox-android --android-device=<device ID>
- -

If you've multiple versions of Firefox installed, you may need to choose a specific version. For example:

- -
web-ext run --target=firefox-android ... --firefox-apk=org.mozilla.firefox
- -

The first time you run this command, you may need to grant Android permissions for the APK. This is because the command needs read / write access to the device storage, so that Firefox for Android can run on a temporary profile. The web-ext output guides you in how to grant these permissions.

- -

The web-ext command does not alter any of your existing Firefox for Android preferences or data. To see more information about how web-ext is interacting with your device, run the command with --verbose.

- -

See the run command reference to learn more.

- -

Depurar no Firefox para Android

- -

When using web-ext run to test an extension on Firefox for Android, you'll notice a message like this in the console output:

- -
You can connect to this Android device on TCP port 51499
-
- -

This is a remote debugger port that you can connect to with Firefox's developer tools. In this case, you'd connect to host localhost on port 51499.

- -

See this guide for more information about debugging an extension on Firefox for Android.

- -

Testar extensões não assinadas

- -

When you execute web-ext run, the extension gets installed temporarily until you close Firefox. This does not violate any signing restrictions. If instead you create a zip file with web-ext build and try to install it into Firefox, you will see an error telling you that the add-on is not signed. You will need to use an unbranded build or use a development build to install unsigned extensions.

- -

Utilizar um perfil personalizado

- -

By default, the run command will create a temporary Firefox profile. To run your extension with a specific profile use the --firefox-profile option, like this:

- -
web-ext run --firefox-profile=your-custom-profile
- -

This option accepts a string containing the name of your profile or an absolute path to the profile directory. This is helpful if you want to manually configure some settings that will always be available to the run command.

- -

Manter alterações de perfil

- -

The run command does not save any changes made to the custom profile specified by --firefox-profile. To keep changes, add this option:

- -
web-ext run --keep-profile-changes --firefox-profile=your-custom-profile
- -

This may be helpful if your extension has many different run states.

- -
-

This option makes the profile specified by --firefox-profile completely insecure for daily use. It turns off auto-updates and allows silent remote connections, among other things. Specifically, it will make destructive changes to the profile that are required for web-ext to operate.

-
- -

Empacotar a sua extensão

- -

Once you've tested your extension and verified that it's working, you can turn it into a package for submitting to addons.mozilla.org using the following command:

- -
web-ext build
- -

This outputs a full path to the generated .zip file that can be loaded into a browser.

- -
-

The generated .zip file doesn't work on Firefox without signing or adding applications.gecko.id key into manifest.json.  For more information, please refer WebExtensions and the Add-on ID page.

-
- -

web-ext build is designed to ignore files that are commonly not wanted in packages, such as .git, node_modules, and other artifacts.

- -

See the build reference guide to learn more.

- -

Assinar a sua extensão para distribuição

- -

As an alternative to publishing your extension on addons.mozilla.org, you can self-host your package file but it needs to be signed by Mozilla first. The following command packages and signs a ZIP file, then returns it as a signed XPI file for distribution:

- -
web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET 
- -

The API options are required to specify your addons.mozilla.org credentials.

- - - -

See the sign reference guide to learn more.

- -

Assinar as extensões sem uma Id. explicita

- -

web-ext supports signing extensions that do not declare the applications.gecko.id property in their manifest. The first time you sign an extension without an explicit ID, addons.mozilla.org will generate an ID and web-ext will save it to .web-extension-id in the working directory. You should save the ID file so that you can sign future versions of the same extension. If you lose the ID file, you will have to add back the applications.gecko.id property or use the --id option when signing, for example:

- -
web-ext sign --api-key=... --api-secret=... --id="{c23c69a7-f889-447c-9d6b-7694be8035bc}"
- -

Assinar num ambiente restringido

- -

If you're working in an environment that restricts access to certain domains, you can try using a proxy when signing:

- -
web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000
- -

See the --api-proxy option to learn more.

- -

The following domains are used for signing and downloading files:

- - - -

Verificar com o código "lint"

- -

Before trying out your extension with the run command or submitting your package to addons.mozilla.org, use the lint command to make sure your manifest and other source files do not contain any errors. Example:

- -
web-ext lint
- -

This uses the addons-linter library to walk through your source code directory and report any errors, such as the declaration of an unknown permission.

- -

See the lint reference guide to learn more.

- -

Definindo as predefinições de opção num ficheiro de configuração

- -

You can specify --config=my-config.js to set default values for any option. Here is an example with the build command:

- -
web-ext --config=my-config.js build
- -

The file should be a CommonJS module as understood by NodeJS and must export each configuration value. Here is how you would set the default value of --verbose to true:

- -
module.exports = {
-  verbose: true,
-};
- -

If you want to specify options that only apply to a specific command, you nest the configuration under the command name. Here is an example of adding configuration for --overwrite-dest that only applies to the build command as well as --firefox that only applies to the run command:

- -
module.exports = {
-  // Global options:
-  verbose: true,
-  // Command options:
-  build: {
-    overwriteDest: true,
-  },
-  run: {
-    firefox: 'nightly',
-  },
-};
- -

To create a configuration key for a command line option, you remove the preceding dashes and convert the name to camel case. As you can see from this example, --overwrite-dest was converted to overwriteDest.

- -

If an option can be specified multiple times on the command line then you define it as an array. For example, here is how to specify multiple --ignore-files patterns:

- -
module.exports = {
-  ignoreFiles: [
-    'package-lock.json',
-    'yarn.lock',
-  ],
-};
- -

Automatic discovery of configuration files

- -

web-ext will load existing configuration files in the following order:

- - - -

If a home directory config and a local directory config define the same option, the value from the latter file will be used.

- -

To disable automatic loading of configuration files, set this option:

- -
web-ext --no-config-discovery run
- -

To diagnose an issue related to config files, re-run your command with --verbose. This will tell you which config file affected which option value.

- -

Specifying different source and destination directories

- -

The preceding commands use default directories for the extension source and artifact creation (for example, built .zip files). The defaults are:

- - - -

You can specify different source and destination directories using the --source-dir and --artifacts-dir options when running your commands. Their values can be relative or absolute paths, but must always be specified as strings. Here is an example of specifying both options when building an extension:

- -
web-ext build --source-dir=webextension-examples/notify-link-clicks-i18n --artifacts-dir=zips
- -

Outputting verbose messages

- -

To see in detail what web-ext is doing when you run a command, include the --verbose option. For example:

- -
web-ext build --verbose
- -

Viewing all commands and options

- -

You can list all commands and options like this:

- -
web-ext --help
- -

You can list options for a specific command by adding it as an argument:

- -
web-ext --help run
- -

Detecting temporary installation

- -

Your extension can detect whether it was installed using web-ext run, rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event and check the value of details.temporary.

- -

Using web-ext from a script

- -

You can use web-ext as a NodeJS module. Here is more information, with example code.

- -

Consulte também

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html deleted file mode 100644 index acc5d21d53..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Publicar a sua extensão -slug: Mozilla/Add-ons/WebExtensions/Publicar_a_sua_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Package_your_extension_ ---- -
{{AddonSidebar}}
- -

 

- -
-
-

Packaged extensions in Firefox are called "XPI files", which are ZIP files with a different extension.

- -

You don't have to use the XPI extension when uploading to AMO.

-
-
- -

 

- -

During development, your extension will consist of a directory containing a manifest.json file and the other files it needs—scripts, icons, HTML documents, and so on. You need to zip these into a single file for uploading to AMO.

- -

If you're using web-ext, use web-ext build to package your extension. Otherwise, follow the instructions below for your chosen operating system.

- -
-

Dica: The ZIP file must be a ZIP of the extension's files themselves, not of the directory containing them.

-
- -

Windows

- -
    -
  1. Abra a pasta com os seus ficheiros da extensão.
  2. -
  3. Selecione todos os ficheiros.
  4. -
  5. Clique direito e escolha "Enviar para" → Pasta Comprimida (zipped).
  6. -
- -

- -

Mac OS X

- -
    -
  1. Open the folder with your extension's files.
  2. -
  3. Select all of the files.
  4. -
  5. Right click and choose Compress n Items.
  6. -
- -

- -
- -
- -

Linux / Mac OS X Terminal

- -
    -
  1. Open Terminal.
  2. -
  3. Open the directory containing your extension's files,  using the command
    - cd path/to/my-extension/
  4. -
  5. ZIP the content of the directory, using the command
    - zip -r -FS ../my-extension.zip *
  6. -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html b/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html deleted file mode 100644 index 51356eed85..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html +++ /dev/null @@ -1,446 +0,0 @@ ---- -title: Scripts de Conteúdo -slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts ---- -
{{AddonSidebar}}
- -

Um script de conteúdo é uma parte da sua extensão que é executada no contexto de uma determinada página da Web (em oposição aos scripts de segundo plano que são parte da própria extensão, ou scripts que são parte do próprio site da Web, tal como aqueles carregados utilizando o {{HTMLElement("script")}} elemento.

- -

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

- -

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

- -

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

- -
-

Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a CSP error.

- -

As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an onboarding page that moves users away from addons.mozilla.org.

-
- -
-

Values added to the global scope of a content script with var foo or window.foo = "bar" may disappear due to bug 1408996.

-
- -

Carregar scripts de conteúdo

- -

You can load a content script into a web page in one of three ways:

- -
    -
  1. at install time, into pages that match URL patterns: using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
  2. -
  3. at runtime, into pages that match URL patterns: using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. This is just like method (1), except you can add and remove content scripts at runtime.
  4. -
  5. at runtime, into specific tabs: using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a browser action.
  6. -
- -

There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

- -

Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a match pattern. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".

- -

Ambiente de script de conteúdo

- -

Acesso DOM

- -

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

- -

However, content scripts get a "clean view of the DOM". This means:

- - - -

In Firefox, this behavior is called Xray vision.

- -

For example, consider a web page like this:

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

The script "page-script.js" does this:

- -
// page-script.js
-
-// add a new element to the DOM
-var p = document.createElement("p");
-p.textContent = "This paragraph was added by a page script.";
-p.setAttribute("id", "page-script-para");
-document.body.appendChild(p);
-
-// define a new property on the window
-window.foo = "This global variable was added by a page script";
-
-// redefine the built-in window.confirm() function
-window.confirm = function() {
-  alert("The page script has also redefined 'confirm'");
-}
- -

Now an extension injects a content script into the page:

- -
// content-script.js
-
-// can access and modify the DOM
-var pageScriptPara = document.getElementById("page-script-para");
-pageScriptPara.style.backgroundColor = "blue";
-
-// can't see page-script-added properties
-console.log(window.foo);  // undefined
-
-// sees the original form of redefined properties
-window.confirm("Are you sure?"); // calls the original window.confirm()
- -

The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.

- -

All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.

- -

One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.

- -

If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

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

Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See Sharing objects with page scripts for more details.

- -

APIs da Extensão da Web

- -

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

- -

From extension:

- - - -

From runtime:

- - - -

From i18n:

- - - -

From menus:

- - - -

Everything from storage.

- -

XHR e Fetch

- -

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

- -

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

- -

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead. For cross-browser extensions their presence must be feature-detected.

- -

Comunicar com scripts de segundo plano

- -

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

- -

There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.

- -

One-off messages

- -

To send one-off messages, with an optional response, you can use the following APIs:

- - - - - - - - - - - - - - - - - - - - - -
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
- -

For example, here's a content script which listens for click events in the web page. If the click was on a link, it messages the background page with the target URL:

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

The background script listens for these messages and displays a notification using the notifications API:

- -
// background-script.js
-
-browser.runtime.onMessage.addListener(notify);
-
-function notify(message) {
-  browser.notifications.create({
-    "type": "basic",
-    "iconUrl": browser.extension.getURL("link.png"),
-    "title": "You clicked a link!",
-    "message": message.url
-  });
-}
-
- -

This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.

- -

Connection-based messaging

- -

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

- -

Each side has a runtime.Port object, which they can use to exchange messages.

- -

To create the connection:

- - - -

Once each side has a port, the two sides can exchange messages using runtime.Port.postMessage() to send a message, and runtime.Port.onMessage to receive messages.

- -

For example, as soon as it loads, this content script:

- - - -
// content-script.js
-
-var myPort = browser.runtime.connect({name:"port-from-cs"});
-myPort.postMessage({greeting: "hello from content script"});
-
-myPort.onMessage.addListener(function(m) {
-  console.log("In content script, received message from background script: ");
-  console.log(m.greeting);
-});
-
-document.body.addEventListener("click", function() {
-  myPort.postMessage({greeting: "they clicked the page!"});
-});
- -

The corresponding background script:

- - - -
// background-script.js
-
-var portFromCS;
-
-function connected(p) {
-  portFromCS = p;
-  portFromCS.postMessage({greeting: "hi there content script!"});
-  portFromCS.onMessage.addListener(function(m) {
-    console.log("In background script, received message from content script")
-    console.log(m.greeting);
-  });
-}
-
-browser.runtime.onConnect.addListener(connected);
-
-browser.browserAction.onClicked.addListener(function() {
-  portFromCS.postMessage({greeting: "they clicked the button!"});
-});
-
- -

Multiple content scripts

- -

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

- - - - - -
// background-script.js
-
-var ports = []
-
-function connected(p) {
-  ports[p.sender.tab.id]    = p
-  //...
-}
-
-browser.runtime.onConnect.addListener(connected)
-
-browser.browserAction.onClicked.addListener(function() {
-  ports.forEach(p => {
-        p.postMessage({greeting: "they clicked the button!"})
-    })
-});
- - - - - -

Comunicar com a página da Web

- -

Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

- -

For example:

- -
// page-script.js
-
-var messenger = document.getElementById("from-page-script");
-
-messenger.addEventListener("click", messageContentScript);
-
-function messageContentScript() {
-  window.postMessage({
-    direction: "from-page-script",
-    message: "Message from the page"
-  }, "*");
- -
// content-script.js
-
-window.addEventListener("message", function(event) {
-  if (event.source == window &&
-      event.data &&
-      event.data.direction == "from-page-script") {
-    alert("Content script received message: \"" + event.data.message + "\"");
-  }
-});
- -

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

- -
-

Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.

- -

To make a trivial example, suppose the content script code that receives the message does something like this:

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

Now the page script can run any code with all the privileges of the content script.

-
- -

Using eval() in content scripts

- -

In Chrome, eval() always runs code in the context of the content script, not in the context of the page.

- -

In Firefox:

- - - -

For example, consider a content script like this:

- -
// content-script.js
-
-window.eval('window.x = 1;');
-eval('window.y = 2');
-
-console.log(`In content script, window.x: ${window.x}`);
-console.log(`In content script, window.y: ${window.y}`);
-
-window.postMessage({
-  message: "check"
-}, "*");
- -

This code just creates some variables x and y using window.eval() and eval(), then logs their values, then messages the page.

- -

On receiving the message, the page script logs the same variables:

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

In Chrome, this will produce output like this:

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

In Firefox the following output is produced:

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

The same applies to setTimeout(), setInterval(), and Function().

- -

When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

- -
// page.js redefines console.log
-
-var original = console.log;
-
-console.log = function() {
-  original(true);
-}
-
- -
// content-script.js calls the redefined version
-
-window.eval('console.log(false)');
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html b/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html deleted file mode 100644 index e34a4013d3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Suporte de navegador para as APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs ---- -

{{AddonSidebar}}

- -
{{WebExtAllCompatTables}}
- -
A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, verifique por favor, consulte https://github.com/mdn/browser-compat-data e envie-nos um pedido de submissão.
- -
 
- -
Agradecimentos - -

Os dados de compatibilidade do Microsoft Edge são fornecidos pela Corporação Microsoft e estão incluídos aqui sob a Licença de Creative Commons Attribution 3.0 - Estado Unidos.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html b/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html deleted file mode 100644 index 006ecce85c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Conversão de uma extensão do Google Chrome -slug: Mozilla/Add-ons/WebExtensions/Trasnsferir_extensao_Google_Chrome -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension ---- -
{{AddonSidebar}}
- -

As extensões desenvolvidas com as APIs de Extensão da Web são preparadas para compatibilidade entre navegadores: em grande medida, a tecnologia é diretamente compatível com a API de extensão suportada pelo Google Chrome e Opera. As extensões escritas para estes navegadores irão, na maioria do casos, ser executadas no Firefox com apenas algumas alterações. Quase todas das  APIs de extensão são suportadas, utilizando as funções de chamada sob o espaço de nome  chrome, o mesmo que Chrome. As únicas APIs que não são suportadas no nome de espaço chrome são aquelas que são intentionalmente incompatíveis com o Chrome. Nesses casos, a página da documentação de API irá declarar explicitamente que só é suportado no espaço do nome browser . O processo de transferir uma extensão do Chrome para Opera é como isto:

- -
    -
  1. Reveja a sua utilização das funcionaldiades de manifest.json e APIs da Extensão da Web contra a referência de incompatibilidade do Chrome. Se estiver a utilizar as funcionalidades ou APIs que ainda não são suportadas no Firefox, poderá não conseguir converter ainda a sua extensão. A Mozilla fornece um serviço que pode ajudar a automatizar este passo: Teste de Compatibilidade de Extensão para Firefox (inglês).
  2. -
  3. Instale a sua extensão no Firefox e teste-a.
  4. -
  5. Se tiver quaisquer problemas, contacte-nos em lista de endereços ou #webextensions no IRC.
  6. -
  7. Submeta o seu extra em AMO para assinar e distribuir
  8. -
- -

Se estava dependente da opção da linha de comando do Chrome para carregar uma extensão descompactada, consulte a ferramenta web-ext que automatiza a instalação temporária no Firefox para desenvolvimento.

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html new file mode 100644 index 0000000000..c5da78003b --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html @@ -0,0 +1,50 @@ +--- +title: Botão da Barra de Ferramentas +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador +tags: + - Extensão da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +--- +
{{AddonSidebar}}
+ +

Normalmente referido como uma ação do navegador, esta opção da interface do utilizador é um botão adicionado à barra de ferramentas do navegador. Os utilizadores clicam no botão para interagir com a sua extensão.
+

+ +

The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see Page actions and browser actions.

+ +

Especificar a ação do navegador

+ +

Define as propriedades da ação do navegador utilizando a chave browser_action em manifest.json:

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

The only mandatory key is default_icon.

+ +

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

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

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

+ +

Note that your extension can have only one browser action.

+ +

You can change any of the browser action properties programmatically using the browserAction API.

+ +

Ícones

+ +

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

+ +

Exemplos

+ +

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html new file mode 100644 index 0000000000..bc2f1bd2da --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html @@ -0,0 +1,453 @@ +--- +title: Estilos de navegador +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador +tags: + - Extensões + - Extensões da Web + - Extras +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles +--- +
{{AddonSidebar}}
+ +

Certain user interface components - browser and page action popups, sidebars, and options pages - are specified by your extension in essentially the same way:

+ +
    +
  1. create an HTML file defining the structure of the UI element
  2. +
  3. add a manifest.json key (browser_action, page_action, sidebar_action, or options_ui) pointing to that HTML file.
  4. +
+ +

One of the challenges with this approach is styling the element in such a way that it fits in with the browser's own style. To help with this, the manifest.json keys include an extra optional property: browser_style. If this is included and set to true, then your document will get one or more extra stylesheets that will help make it look consistent with the browser's UI and with other extensions that use the browser_style property.

+ +

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css. The extra stylesheet at chrome://browser/content/extension-mac.css is also included on OS X.

+ +

Most styles are automatically applied, but some elements require you to add the non-​standard browser-style class to get their styling since Firefox 55, as detailed in the table below:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ElementoExemplo
<button> +
+<button class="browser-style">Click me</button>{{non-standard_inline}}
+
+

<select>

+
+
+<select class="browser-style" name="select">
+  <option value="value1">Value 1</option>
+  <option value="value2" selected>Value 2</option>
+  <option value="value3">Value 3</option>
+</select>
+
<textarea> +
+<textarea class="browser-style">Write here</textarea>
+
Parent of an <input> +
+<div class="browser-style">
+  <input type="radio" id="op1" name="choices" value="op1">
+  <label for="op1">Option 1</label>
+
+  <input type="radio" id="op2" name="choices" value="op2">
+  <label for="op2">Option 2</label>
+</div>
+
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Componentes de Painel do Firefox

+ +
+

{{NonStandardBadge(1)}} Non-Standard
+ This feature is non-standard and only works in Firefox.

+
+ +

The chrome://browser/content/extension.css stylesheet also contains the styles for the Firefox Panel Components.

+ +

The legacy Firefox Style Guide documents proper usage.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ElementoExemplo
Cabeçalho +
+<header class="panel-section panel-section-header">
+  <div class="icon-section-header"><img src="image.svg"/></div>
+  <div class="text-section-header">Header</div>
+</header>
+
Rodapé +
+<footer class="panel-section panel-section-footer">
+  <button class="panel-section-footer-button">Cancel</button>
+  <div class="panel-section-footer-separator"></div>
+  <button class="panel-section-footer-button default">Confirm</button>
+</footer>
+
Separadores +
+<div class="panel-section panel-section-tabs">
+  <button class="panel-section-tabs-button selected">Tab</button>
+  <div class="panel-section-tabs-separator"></div>
+  <button class="panel-section-tabs-button">Tab</button>
+  <div class="panel-section-tabs-separator"></div>
+  <button class="panel-section-tabs-button">Tab</button>
+</div>
+
Form +
+<div class="panel-section panel-section-formElements">
+  <div class="panel-formElements-item">
+    <label for="name01">Label:</label>
+    <input type="text" value="Name" id="name01" />
+  </div>
+  <div class="panel-formElements-item">
+    <label for="picker01">Label:</label>
+    <select id="picker01">
+      <option value="value1" selected="true">Dropdown</option>
+      <option value="value2">List Item</option>
+      <option value="value3">List Item</option>
+    </select>
+  </div>
+  <div class="panel-formElements-item">
+    <label for="placeholder01">Label:</label>
+    <input type="text" placeholder="Placeholder" id="placeholder01" />
+    <button name="expander" class="expander"></button>
+  </div>
+</div>
+
Menu +
+<div class="panel-section panel-section-list">
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut">Ctrl-L</div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item disabled">
+    <div class="icon"></div>
+    <div class="text">Disabled List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+</div>
+
+ +

Exemplo

+ +

HTML

+ +
<header class="panel-section panel-section-header">
+  <div class="icon-section-header"><!-- An image goes here. --></div>
+  <div class="text-section-header">Header</div>
+</header>
+
+<div class="panel-section panel-section-list">
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut">Ctrl-L</div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item disabled">
+    <div class="icon"></div>
+    <div class="text">Disabled List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+</div>
+
+<footer class="panel-section panel-section-footer">
+  <button class="panel-section-footer-button">Cancel</button>
+  <div class="panel-section-footer-separator"></div>
+  <button class="panel-section-footer-button default">Confirm</button>
+</footer>
+ + + +

Result

+ +

{{EmbedLiveSample("Example","640","360")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html new file mode 100644 index 0000000000..231a800bc3 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html @@ -0,0 +1,51 @@ +--- +title: Itens do menu de contexto +slug: >- + Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items +--- +
{{AddonSidebar}}
+ +
+

Essa opção da interface do utilizador adiciona um ou mais itens a um menu de contexto do navegador.

+ +

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

+ +

You would use this option to expose features that are relevant to specific browser or web page contexts. For example, you could show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("contextMenus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("contextMenus.remove")}}.

+ +

Especificar itens do menu de contexto

+ +

You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the contextMenus permission in your manifest.json to be able to take advantage of the API.

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

You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:

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

Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.

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

Exemplos

+ +

O repositório de wexemplos das Extensões da Web no GitHub, contém vários exemplos de extensões que utilizam os itens do menu de contexto:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html new file mode 100644 index 0000000000..a2bc9921ad --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html @@ -0,0 +1,62 @@ +--- +title: Painéis das ferramentas de desenvolvimento +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels +tags: + - Extensões da Web + - Guía + - Interface do Utilizador + - Principiante +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels +--- +
{{AddonSidebar}}
+ +
+

Esta funcionalidade está disponível desde o Firefox 54.

+
+ +

Quando uma extensão fornece ferramentas que são úteis para os programadores, é possível adicionar uma IU para as mesmas para as ferramentas de desenvolvimento do navegador como um novo painel.

+ +

Simple example showing the addition of "My panel" to the Developer Tools tabs.

+ +

Especificar um painel de ferramentas de desenvolvimento

+ +

Um painél das ferramentas de desenvovlimento é adicionado utilizando a API devtools.panels, que precisa de ser executada a partir de uma página de devtools especial.

+ +

Adicione a páginas de devtools, incluindo a chave devtools_page na extensão de manifest.json e forneça a localização do ficheiro HTML da página na extensão:

+ +
"devtools_page": "devtools-page.html"
+ +

From the devtools page, call a script that will add the devtools panel:

+ +
<body>
+  <script src="devtools.js"></script>
+</body>
+ +

In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:

+ +
function handleShown() {
+  console.log("panel is being shown");
+}
+
+function handleHidden() {
+  console.log("panel is being hidden");
+}
+
+browser.devtools.panels.create(
+  "My Panel",           // title
+  "icons/star.png",           // icon
+  "devtools/panel/panel.html"          // content
+).then((newPanel) => {
+  newPanel.onShown.addListener(handleShown);
+  newPanel.onHidden.addListener(handleHidden);
+});
+ +

The extension can now run code in the inspected window using devtools.inspectedWindow.eval() or by injecting a content script via the background script by passing a message. You can find more details on how to do this in Extending the developer tools.

+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html new file mode 100644 index 0000000000..4bf94b9653 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html @@ -0,0 +1,64 @@ +--- +title: Páginas de extensão +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages +--- +
{{AddonSidebar()}}
+ +

Pode inclur páginas html na sua extensão para fornecer formulários, ajuda, ou qualquer outro conteúdo que a sua extensão precisar.

+ +

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

+ +

These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts.

+ +

Especificar páginas de extensão

+ +

You can include HTML files, and their associated CSS or JavaScript files, in your extension. The files can be included in the root or organized within meaningful sub-folders.

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

Exibir páginas de extensão

+ +

There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}.

+ +

Using windows.create(), for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience:

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

When the window is no longer needed, it can be closed programmatically, for example, after the user clicks a button, by passing the id of the current window to {{WebExtAPIRef("windows.remove()")}}:

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

Páginas de extensão e histório

+ +

By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record:

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

To use the history API, you must request the "history" permission in your manifest.json file.

+ +

Desenho da página da Web

+ +

For details on how to design your web page's to match the style of Firefox, see the Photon Design System documentation.

+ +

Exemplos

+ +

The webextensions-examples repository on GitHub includes the window-manipulator example, which implements several of the options for creating windows.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html new file mode 100644 index 0000000000..6ec29a7fcf --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html @@ -0,0 +1,93 @@ +--- +title: Interface do utilizador +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador +tags: + - Interface do Utilizador + - Landing + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/user_interface +--- +
{{AddonSidebar}}
+ +

As extensões que utilizam as APIs de WebExtension são fornecidas com várias opções de interface do utilizador, e assim, as suas funcionalidades podem ficar disponíveis para o utilizador. Um resumo dessas opções é fornecido abaixo, com uma introdução mais detalhada para cada opção da interface do utilziador nesta secção .

+ +
+

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Opção de UIDescriçãoExemplo
Browser toolbar buttonA button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example of a WebExtension toolbar button
Browser toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a WebExtension toolbar button with a popup
Address bar buttonA button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemsMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.
Sidebar +

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

+
Example of a WebExtension's sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page in the from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Bundled web pagesUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationsTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example notification from a WebExtension
Address bar suggestionsOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelsA tab with an associated HTML document that displays in the browser's developer tools.New panel tab in the Developer Tools tab bar
+ +

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html new file mode 100644 index 0000000000..5b38d4f29f --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html @@ -0,0 +1,50 @@ +--- +title: Notificações +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications +--- +
{{AddonSidebar}}
+ +
+

As notificações permitem-lhe comunicar a informação sobre a sua extensão ou o seu conteúdo utilizando o serviço de notificação do sistema operativo subjacente:

+ +

+ +

As notificações podem incluir uma chamada para ação para o utilizador, e o seu extra pode escutar o utilizador a clicar na notificação ou a notificação a fechar.

+ +

Especificar as notificações

+ +

Pode gerir as notificações programaticamente, utilizando a API {{WebExtAPIRef("notifications")}}. Para utilizar esta API deve solicitar a permissão de notifications no seu manifest.json:

+ +
"permissions": ["notifications"]
+ +

Depois, pode utilziar {{WebExtAPIRef("notifications.create")}} para criar as suas notificações, como neste exemplo de notify-link-clicks-i18n:

+ +
var title = browser.i18n.getMessage("notificationTitle");
+var content = browser.i18n.getMessage("notificationContent", message.url);
+browser.notifications.create({
+  "type": "basic",
+  "iconUrl": browser.extension.getURL("icons/link-48.png"),
+  "title": title,
+  "message": content
+});
+ +

Este código cria uma notificação com um ícone, título, e mensagem.

+ +

Se a notificação incluir uma chamada para ação, pode escutar o utilizador a clicar na notificação para chamar a ação para manipular a ação:

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

Se estiver a enviar chamadas para ação através das notificações, também irá querer definir a notificação opcional id, e assim, pode saber qual a chamada para ação que o utilizador selecionou.

+ +

Exemplos

+ +

O repositório dos exemplos da extensões da Web no GitHub, contém vários exemplos das extensões que utilizam creates notifications:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html new file mode 100644 index 0000000000..c0f9f41dca --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html @@ -0,0 +1,70 @@ +--- +title: Sugestões da barra de endereço +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox +tags: + - Extensões da Web + - Interface do Utilizador +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox +--- +
{{AddonSidebar()}}
+ +

Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword.

+ +

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

+ +

This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples.

+ +

Especificando a personalização de omnibox

+ +

You tell your extension that it is going to customize the address bar suggestions by including the omnibox key and definition of the trigger keyword in its manifest.json file:

+ +
  "omnibox": { "keyword" : "cs" }
+ +

In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature:

+ +
browser.omnibox.setDefaultSuggestion({
+  description: `Search the firefox codebase
+    (e.g. "hello world" | "path:omnibox.js onInputChanged")`
+});
+ +

You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a search of https://searchfox.org/mozilla-central using the term entered by the user:

+ +
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
+  let headers = new Headers({"Accept": "application/json"});
+  let init = {method: 'GET', headers};
+  let url = buildSearchURL(text);
+  let request = new Request(url, init);
+
+  fetch(request)
+    .then(createSuggestionsFromResponse)
+    .then(addSuggestions);
+});
+ +

If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down.

+ +

The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened:

+ +
browser.omnibox.onInputEntered.addListener((text, disposition) => {
+  let url = text;
+  if (!text.startsWith(SOURCE_URL)) {
+    // Update the url if the user clicks on the default suggestion.
+    url = `${SEARCH_URL}?q=${text}`;
+  }
+  switch (disposition) {
+    case "currentTab":
+      browser.tabs.update({url});
+      break;
+    case "newForegroundTab":
+      browser.tabs.create({url});
+      break;
+    case "newBackgroundTab":
+      browser.tabs.create({url, active: false});
+      break;
+  }
+});
+ +

 

+ +

Exemplos

+ +

O repositório dos exemplos das extensões da Web no GitHub inclui o exemplo firefox-code-search que personaliza a barra de pesquisa.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html new file mode 100644 index 0000000000..b3bee11990 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html @@ -0,0 +1,64 @@ +--- +title: Página de opções +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages +--- +
{{AddonSidebar}}
+ +
+

Uma página de Opções permite-lhe definir as preferências para sua extensão que os seus utilizadores podem alterar. Os utilizadores podem aceder á página das opções para uma extensão a partir do do gestor de extras do navegador:

+ +

{{EmbedYouTube("02oXAcbUv-s")}}

+ +

The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another.

+ + + +

You can open the page programmatically by calling runtime.openOptionsPage().

+ +

Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details.

+ +

Especificar a página de opções

+ +

To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the favourite-colour example, includes a JavaScript file:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+  </head>
+
+<body>
+  <form>
+      <label>Favourite colour</label>
+      <input type="text" id="colour" >
+      <button type="submit">Save</button>
+  </form>
+  <script src="options.js"></script>
+</body>
+
+</html>
+ +

JavaScript em execução na página pode utilizar a API das Extensões da Web que o extra tem permissões para. Em particular, pode utilziar a APi de armazenamento para manter as preferências.

+ +

Package the page's files in your extension.

+ +

You also need to include the options_ui key in your manifest.json file, giving it the URL to the page.

+ +
"options_ui": {
+  "page": "options.html",
+  "browser_style": true
+},
+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use an options page:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html new file mode 100644 index 0000000000..7093d3355c --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html @@ -0,0 +1,50 @@ +--- +title: Botão da barra de endereço +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina +tags: + - Extensões da Web + - Interface do Utilizador +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions +--- +
{{AddonSidebar}}
+ +

Normalmente referido como uma ação da página, esta opção da inteface do utilizador é um botão adicionado à barra de endereço do navegador. Os utilziadores clicam no botão para interagir com a sua extensão.

+ +

+ +

Use this button when a feature is only relevant for some web pages. By default, the address bar button is hidden in all browser tabs, and you call pageAction.show() and pageAction.hide() to show or hide it in specific tabs.

+ +

Compare to the toolbar button, which offers similar behavior but is used in situations where the extension's features are applicable to almost every web page.

+ +

Especificar a ação da página

+ +

You define the page action's properties using the page_action key in manifest.json:

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

The only mandatory key is default_icon.

+ +

There are two ways to specify a page action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using pageAction.onClicked:

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

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

+ +

Note that your extension can have one page action only.

+ +

You can change any of the page action properties programmatically using the pageAction API.

+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use page action:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html new file mode 100644 index 0000000000..6bbf3f7ce8 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html @@ -0,0 +1,60 @@ +--- +title: Janelas (Popups) +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups +tags: + - Extensions + - IU + - Interface do Utilizador + - Janela + - popup +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups +--- +
{{AddonSidebar}}
+ +
+

Uma janela (popup) é uma janela que está associada com um botão da barra de ferramentas ou botão da barra de endereço.

+ +

+ +

Quando o usuário clica no botão, a janela popup é exibida. Quando o usuário clica em qualquer lugar fora do popup, ele é fechado. O popup pode ser fechado via programação usando a função window.close() em um script sendo executado no popup. Entretanto, você não pode abrir o popup via programação a partir do código JavaScript da extensão: ele somente se abre em resposta a uma ação do usuário.

+ +

Você pode definir um atalho de teclado que abre o popup usando "_execute_browser_action" and "_execute_page_action". Veja a documentação da chave commands       no manifest.json.

+ +

Especificar uma janela

+ +

O popup é definido por um arquivo HTML, que pode incluir arquivos CSS e JavaScript, como uma página comum. Diferentemente de uma página comum, o código JavaScript pode usar todos os WebExtension APIs que a extensão tem permissions .

+ +

O documento do popup é carregado toda vez que ele é exibido, e descarregado quando o popup é fechado.

+ +

O arquivo HTML é incluído na extensão e especificado como parte do  browser_action ou chave page_action por "default_popup" no arquivo manifest.json:

+ +
  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  }
+ +

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

+ +

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

+ +

Depurar janelas

+ +

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

+ +

Redimensionar janelas

+ +

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

+ +

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

+ +

No Firefox Android 57, popup é mostrada como uma página normal num novo separador.

+ +

Desenho de janela

+ +

Para obter detalhes sobre como desenhar a sua janela (popup) da página da Web para combinar com o estilo do Firefox, consulte a documentação Photon Design System.

+ +

Exemplos

+ +

The webextensions-examples  repository on GitHub includes the beastify example which implements a browser action with a popup.

+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html new file mode 100644 index 0000000000..2cfa1800a7 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html @@ -0,0 +1,57 @@ +--- +title: Barras laterais +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars +--- +
{{AddonSidebar}}
+ +
+

 

+ +

Uma barra lateral é um painel que é exibido no lado esquerdo da janela do navegador, ao lado da página da Web. O navegador fornece uma IU que permite ao utilizador ver as barras laterais atualmente disponíveis e selecionar uma barra lateral para exibir. Por exemplo, o Firefox tem um menu 'Ver -> Barra lateral'. Apenas pode ser exibida uma barra lateral de cada vez, e essa barra lateral será exibida para todos os separadores e todas as janelas do navegador.

+ +

O navegador poderá incluir uma série de barras laterais integradas. Por exemplo, o Firefox inclui uma barra lateral para interagir com marcadores:

+ +

Using the sidebar_action manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars.

+ +

Like a browser action popup, you specify the sidebar's contents as an HTML document. When the user opens the sidebar, its document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well.

+ +

You can set a document for a particular tab using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API:

+ +
// sidebar.js
+browser.windows.getCurrent({populate: true}).then((windowInfo) => {
+  myWindowId = windowInfo.id;
+});
+ +

This is useful if a sidebar wants to display different content for different windows. For an example of this, see the "annotate-page" example.

+ +

Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

+ +

Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages.

+ +

When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for extension to open sidebars programmatically: sidebars can only be opened by the user.

+ +

Especificar barras laterais

+ +

To specify a sidebar, define the default document with the sidebar_action manifest.json key, alongside a default title and icon:

+ +
"sidebar_action": {
+  "default_title": "My sidebar",
+  "default_panel": "sidebar.html",
+  "default_icon": "sidebar_icon.png"
+}
+ +

You can change the title, panel, and icon programmatically using the {{WebExtAPIRef("sidebarAction")}} API.

+ +

Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox.

+ +

Exemplo

+ +

O repositório de exemplos das extensões da Web no GitHub, contém vários exemplos de extensões que utilizam a barra lateral:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html new file mode 100644 index 0000000000..c2d7ef5d71 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html @@ -0,0 +1,59 @@ +--- +title: O que são extensões? +slug: Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions +tags: + - Extensões + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +
{{AddonSidebar}}
+ +

Uma extensão adiciona funcionalidades e funções a um navegador. É criada, utilizando a tecnologia padrão baseada na Web - CSS, HTML e JavaScript. Esta tira vantagem de algumas APIs da Web, como JavaScript pode em uma página da web, mas uma extensão também tem acesso ao seu próprio conjunto de APIs de JavaScript. Isto significa que pode fazer muito mais numa extensão do que pode com o código numa página da Web. Aqui estão apenas alguns exemplos das coisas que pode fazer.

+ +

Melhore ou complemente um site da Web: utilize um extra para fornecer funcionalidades adicionais no navegador ou informação do seu site da Web. Permita que os utilizadores recolham detalhes das páginas que eles visitam, para melhorar o serviço que oferece.

+ +

+ +

Exemplos: Amazon Assistant para Firefox, OneNote Web Clipper, e Grammarly for Firefox

+ +

Deixe que os utilizadores mostrem a sua personalidade: Browser extensions can manipulate the content of pages browsed by a user. Help the user add a favorite logo or picture as the background to every page they visit. Extensions also give you the ability to update the look of the Firefox UI. (Update the Firefox UI using standalone theme add-ons too).

+ +

+ +

Exemplos: MyWeb New Tab, Tabliss, e VivaldiFox

+ +

Adicionar ou remover conteúdo das páginas da Web: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page’s HTML and CSS, you can help users see the web the way they want to.

+ +

+ +

Exemplos: uBlock Origin, Reader, e Toolbox para Google Play Store™

+ +

Adicionar ferramentas e novas funcionalidades de navegação: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website’s features or functionality, it doesn't have to be your website.

+ +

+ +

Examples: QR Code Image Generator, Swimlanes for Trello, and Tomato Clock

+ +

Jogos: Offer traditional computer games, with off-line play features, but also explore new game possibilities, for example, by incorporating gameplay into everyday browsing.

+ +

 

+ +

Examples: Asteroids in Popup, Solitaire Card Game New Tab, and 2048 Prime.

+ +

Adicionar ferramentas de desenvolvimento: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar.

+ +

+ +

Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools

+ +

Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.

+ +

If you have ideas or questions, or need help migrating a legacy add-on to WebExtensions APIs, you can reach us on the dev-addons mailing list or in #extdev on IRC.

+ +

E a seguir?

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html new file mode 100644 index 0000000000..f16f7e619b --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html @@ -0,0 +1,60 @@ +--- +title: E a seguir? +slug: Mozilla/Add-ons/WebExtensions/E_a_seguir +tags: + - Extensão da Web + - Extensões + - Principiante +translation_of: Mozilla/Add-ons/WebExtensions/What_next_ +--- +
{{AddonSidebar}}
+ +

Agora, irá estar pronto para começar a transformar a sua ideia de uma extensão de navegador em realidade. Antes de começar essa jornada, vale a pena estar ciente de algumas coisas que irão ajudar a facilitar.

+ +

O seu ambiente de desenvolvimento

+ +

You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things.

+ +

If you use minification or obfuscation tools to deliver your final code, you’ll need to provide your source code to the AMO review process. Also, the tools you use—those for minification,  obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer’s computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools.

+ +

Learn more about build tools

+ +

Bibliotecas de terceiros

+ +

Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way.

+ +

Learn more about submitting source code

+ +

O Acordo de Distribuição do Extra do Firefox

+ +

Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience.

+ +

Leia o acordo

+ +

Learn more about signing

+ +

O processo de revisão

+ +

When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it’s passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it’s easy to check and avoid any likely review problems.

+ +

Check out the review policy and guidelines

+ +

Extensões do navegador em destaque no AMO

+ +

If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser’s add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured.

+ +

Saiba mais sobre como colocar os seus extras em destaque

+ +

Continue a sua experiência de aprendizagem

+ +

Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you’ll discover:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..21b34f2e2c --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,153 @@ +--- +title: A sua primeira extensão +slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao +tags: + - Extensões da Web + - Guía +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +
{{AddonSidebar}}
+ +

Neste artigo, nós iremos abordar a criação de uma extensão para o Firefox, do início até ao fim. A extensão adiciona apenas um contorno vermelho a qualquer página carregada de 'mozilla.org' ou qualquer um dos seus subdomínios.

+ +

O código fonte para este exemplo está no GitHub: borderify.

+ +

Primeiro, precisa de ter o Firefox - versão 45 ou superior.

+ +

Escrever a extensão

+ +

Crie uma nova diretoria e vá para a mesma:

+ +
mkdir borderify
+cd borderify
+ +

manifest.json

+ +

Now create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Borderify",
+  "version": "1.0",
+
+  "description": "Adds a red border to all webpages matching mozilla.org.",
+
+  "icons": {
+    "48": "icons/border-48.png"
+  },
+
+  "content_scripts": [
+    {
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ]
+
+}
+ + + +

The most interesting key here is content_scripts, which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains.

+ + + +
+

In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the  applications key in manifest.json and set its gecko.id property:

+ +
"applications": {
+  "gecko": {
+    "id": "borderify@example.com"
+  }
+}
+
+ +

icons/border-48.png

+ +

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png".

+ +

Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png".  You could use the one from our example, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike license.

+ +

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

+ +
"icons": {
+  "48": "icons/border-48.png",
+  "96": "icons/border-96.png"
+}
+ +

Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.)

+ + + +

borderify.js

+ +

Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content:

+ +
document.body.style.border = "5px solid red";
+ +

This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself.

+ + + +

Testá-la

+ +

Primeiro, reverifique que tem os ficheiros corretos nos locais certos:

+ +
borderify/
+    icons/
+        border-48.png
+    borderify.js
+    manifest.json
+ +

Instalar

+ +

Open "about:debugging" in Firefox, click "Load Temporary Add-on" and select any file in your extension's directory:

+ +

{{EmbedYouTube("cer9EUKegG4")}}

+ +

The extension will now be installed, and will stay until you restart Firefox.

+ +

Alternatively, you can run the extension from the command line using the web-ext tool.

+ +

Testar

+ +

Now try visiting a page under "mozilla.org", and you should see the red border round the page:

+ +

{{EmbedYouTube("rxBQl2Z9IBQ")}}

+ +
+

Don't try it on addons.mozilla.org, though! Content scripts are currently blocked on that domain.

+
+ +

Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extensions's files by clicking the "Reload" button in about:debugging. You can see the changes right away:

+ +

{{EmbedYouTube("NuajE60jfGY")}}

+ + + +

Empacotar e publicação

+ +

Para que as outras pessoas utilizem a sua extensão, precisa de empacotá-la e enviá-la para a assinar na Mozilla. Para saber mais sobre isto, consulte "Publicar a sua extensão".

+ +

E a seguir?

+ +

Agora tem uma idéia do processo de desenvolvimento de uma Extensão da Web para o Firefox, tente:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..503f2b4ae9 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,460 @@ +--- +title: A sua segunda extensão +slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +--- +
{{AddonSidebar}} +

Se já leu o artigo da A sua primeira extensão, já tem uma ideia de como escrever uma extensão. Neste artigo, nós iremos escrever uma extensão um pouco mais complexa que demonstra algumas mais das APIs. 
+
+ A extensão adiciona um novo botão à barra de ferramentas do Firefox. Quando o utilizador clica no botão, nós exibimos uma janela que lhes permite escolher um animal. Uma vez que eles escolhem um animal, nós iremos substituir o conteúdo da página atual com uma fotografia do animal escolhido. 
+
+ Para implementar isto, nós iremos:.

+ +

To implement this, we will:

+ + + +

You could visualise the overall structure of the extension like this:

+ +

+ +

It's a simple extension, but shows many of the basic concepts of the WebExtensions API:

+ + + +

You can find complete source code for the extension on GitHub.

+ +

To write this extension, you'll need Firefox 45 or newer.

+ +

Escrever a extensão

+ +

Create a new directory and navigate to it:

+ +
mkdir beastify
+cd beastify
+ +

manifest.json

+ +

Now create a new file called "manifest.json", and give it the following contents:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Beastify",
+  "version": "1.0",
+
+  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
+  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
+  "icons": {
+    "48": "icons/beasts-48.png"
+  },
+
+  "permissions": [
+    "activeTab"
+  ],
+
+  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  },
+
+  "web_accessible_resources": [
+    "beasts/frog.jpg",
+    "beasts/turtle.jpg",
+    "beasts/snake.jpg"
+  ]
+
+}
+
+ + + +

Note that all paths given are relative to manifest.json itself.

+ +

O ícone

+ +

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png".

+ +

Create the "icons" directory and save an icon there named "beasts-48.png".  You could use the one from our example, which is taken from the Aha-Soft’s Free Retina iconset, and used under the terms of its license.

+ +

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

+ +
"icons": {
+  "48": "icons/beasts-48.png",
+  "96": "icons/beasts-96.png"
+}
+ +

O botão de barra de ferramentas

+ +

The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png".

+ +

Save an icon named "beasts-32.png" in the "icons" directory. You could use the one from our example, which is taken from the IconBeast Lite icon set and used under the terms of its license.

+ +

If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.

+ +

A janela (popup)

+ +

The function of the popup is to enable the user to choose one of three beasts.

+ +

Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:

+ + + +
mkdir popup
+cd popup
+touch choose_beast.html choose_beast.css choose_beast.js
+
+ +

choose_beast.html

+ +

The HTML file looks like this:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+    <link rel="stylesheet" href="choose_beast.css"/>
+  </head>
+
+<body>
+  <div id="popup-content">
+    <div class="button beast">Frog</div>
+    <div class="button beast">Turtle</div>
+    <div class="button beast">Snake</div>
+    <div class="button reset">Reset</div>
+  </div>
+  <div id="error-content" class="hidden">
+    <p>Can't beastify this web page.</p><p>Try a different page.</p>
+  </div>
+  <script src="choose_beast.js"></script>
+</body>
+
+</html>
+
+ +

We have a <div> element with an ID of "popup-content" that contains an element for each animal choice. We have another <div> with an ID of "error-content" and a class "hidden". We'll use that in case there's a problem initializing the popup.

+ +

Note that we include the CSS and JS files from this file, just like a web page.

+ +

choose_beast.css

+ +

The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with class="hidden": this means that our "error-content" <div> will be hidden by default.

+ +
html, body {
+  width: 100px;
+}
+
+.hidden {
+  display: none;
+}
+
+.button {
+  margin: 3% auto;
+  padding: 4px;
+  text-align: center;
+  font-size: 1.5em;
+  cursor: pointer;
+}
+
+.beast:hover {
+  background-color: #CFF2F2;
+}
+
+.beast {
+  background-color: #E5F2F2;
+}
+
+.reset {
+  background-color: #FBFBC9;
+}
+
+.reset:hover {
+  background-color: #EAEA9D;
+}
+
+
+ +

choose_beast.js

+ +

Here's the JavaScript for the popup:

+ +
/**
+ * CSS to hide everything on the page,
+ * except for elements that have the "beastify-image" class.
+ */
+const hidePage = `body > :not(.beastify-image) {
+                    display: none;
+                  }`;
+
+/**
+ * Listen for clicks on the buttons, and send the appropriate message to
+ * the content script in the page.
+ */
+function listenForClicks() {
+  document.addEventListener("click", (e) => {
+
+    /**
+     * Given the name of a beast, get the URL to the corresponding image.
+     */
+    function beastNameToURL(beastName) {
+      switch (beastName) {
+        case "Frog":
+          return browser.extension.getURL("beasts/frog.jpg");
+        case "Snake":
+          return browser.extension.getURL("beasts/snake.jpg");
+        case "Turtle":
+          return browser.extension.getURL("beasts/turtle.jpg");
+      }
+    }
+
+    /**
+     * Insert the page-hiding CSS into the active tab,
+     * then get the beast URL and
+     * send a "beastify" message to the content script in the active tab.
+     */
+    function beastify(tabs) {
+      browser.tabs.insertCSS({code: hidePage}).then(() => {
+        let url = beastNameToURL(e.target.textContent);
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "beastify",
+          beastURL: url
+        });
+      });
+    }
+
+    /**
+     * Remove the page-hiding CSS from the active tab,
+     * send a "reset" message to the content script in the active tab.
+     */
+    function reset(tabs) {
+      browser.tabs.removeCSS({code: hidePage}).then(() => {
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "reset",
+        });
+      });
+    }
+
+    /**
+     * Just log the error to the console.
+     */
+    function reportError(error) {
+      console.error(`Could not beastify: ${error}`);
+    }
+
+    /**
+     * Get the active tab,
+     * then call "beastify()" or "reset()" as appropriate.
+     */
+    if (e.target.classList.contains("beast")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(beastify)
+        .catch(reportError);
+    }
+    else if (e.target.classList.contains("reset")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(reset)
+        .catch(reportError);
+    }
+  });
+}
+
+/**
+ * There was an error executing the script.
+ * Display the popup's error message, and hide the normal UI.
+ */
+function reportExecuteScriptError(error) {
+  document.querySelector("#popup-content").classList.add("hidden");
+  document.querySelector("#error-content").classList.remove("hidden");
+  console.error(`Failed to execute beastify content script: ${error.message}`);
+}
+
+/**
+ * When the popup loads, inject a content script into the active tab,
+ * and add a click handler.
+ * If we couldn't inject the script, handle the error.
+ */
+browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
+.then(listenForClicks)
+.catch(reportExecuteScriptError);
+
+
+ +

The place to start here is line 96. The popup script executes a content script in the active tab as soon as the popup is loaded, using the browser.tabs.executeScript() API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page.

+ +

A common reason the browser.tabs.executeScript() call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the addons.mozilla.org domain. If it does fail, reportExecuteScriptError() will hide the "popup-content" <div>, show the "error-content" <div>, and log an error to the console.

+ +

If executing the content script is successful, we call listenForClicks(). This listens for clicks on the popup.

+ + + +

The beastify() function does three things:

+ + + +

The reset() function essentially undoes a beastify:

+ + + +

O script de conteúdo

+ +

Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents:

+ +
(function() {
+  /**
+   * Check and set a global guard variable.
+   * If this content script is injected into the same page again,
+   * it will do nothing next time.
+   */
+  if (window.hasRun) {
+    return;
+  }
+  window.hasRun = true;
+
+  /**
+   * Given a URL to a beast image, remove all existing beasts, then
+   * create and style an IMG node pointing to
+   * that image, then insert the node into the document.
+   */
+  function insertBeast(beastURL) {
+    removeExistingBeasts();
+    let beastImage = document.createElement("img");
+    beastImage.setAttribute("src", beastURL);
+    beastImage.style.height = "100vh";
+    beastImage.className = "beastify-image";
+    document.body.appendChild(beastImage);
+  }
+
+  /**
+   * Remove every beast from the page.
+   */
+  function removeExistingBeasts() {
+    let existingBeasts = document.querySelectorAll(".beastify-image");
+    for (let beast of existingBeasts) {
+      beast.remove();
+    }
+  }
+
+  /**
+   * Listen for messages from the background script.
+   * Call "beastify()" or "reset()".
+  */
+  browser.runtime.onMessage.addListener((message) => {
+    if (message.command === "beastify") {
+      insertBeast(message.beastURL);
+    } else if (message.command === "reset") {
+      removeExistingBeasts();
+    }
+  });
+
+})();
+
+ +

The first thing the content script does is to check for a global variable window.hasRun: if it's set the script returns early, otherwise it sets window.hasRun and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything.

+ +

After that, the place to start is line 40, where the content script listens for messages from the popup, using the browser.runtime.onMessage API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".

+ + + +

As feras

+ +

Finally, we need to include the images of the beasts.

+ +

Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from the GitHub repository, or from here:

+ +

+ +

Testar a extensão

+ +

First, double check that you have the right files in the right places:

+ +
beastify/
+
+    beasts/
+        frog.jpg
+        snake.jpg
+        turtle.jpg
+
+    content_scripts/
+        beastify.js
+
+    icons/
+        beasts-32.png
+        beasts-48.png
+
+    popup/
+        choose_beast.css
+        choose_beast.html
+        choose_beast.js
+
+    manifest.json
+ +

Starting in Firefox 45, you can install extensions temporarily from disk.

+ +

Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your manifest.json file. You should then see the extension's icon appear in the Firefox toolbar:

+ +

{{EmbedYouTube("sAM78GU4P34")}}

+ +

Open a web page, then click the icon, select a beast, and see the web page change:

+ +

{{EmbedYouTube("YMQXyAQSiE8")}}

+ +

Programae a partir da linha de comando

+ +

Pode automatizar o passo da instalação temporária utilizando a ferramenta web-ext. Experimente isto:

+ +
cd beastify
+web-ext run
+
-- cgit v1.2.3-54-g00ecf