From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- files/pt-pt/mozilla/add-ons/index.html | 111 ----- .../anatomy_of_a_webextension/index.html | 136 ------ .../webextensions/api/browseraction/index.html | 127 ------ .../webextensions/api/browsingdata/index.html | 130 ------ .../api/browsingdata/removeplugindata/index.html | 124 ------ .../webextensions/api/devtools/panels/index.html | 104 ----- .../add-ons/webextensions/api/i18n/index.html | 93 ----- .../mozilla/add-ons/webextensions/api/index.html | 13 - .../webextensions/api/pageaction/index.html | 108 ----- .../webextensions/api/sidebaraction/index.html | 182 -------- .../add-ons/webextensions/api/storage/index.html | 106 ----- .../browser_support_for_javascript_apis/index.html | 20 - .../webextensions/content_scripts/index.html | 447 -------------------- .../add-ons/webextensions/examples/index.html | 29 -- .../extending_the_developer_tools/index.html | 157 ------- .../pt-pt/mozilla/add-ons/webextensions/index.html | 135 ------ .../intercept_http_requests/index.html | 161 ------- .../webextensions/internationalization/index.html | 417 ------------------- .../manifest.json/browser_action/index.html | 236 ----------- .../browser_specific_settings/index.html | 107 ----- .../manifest.json/devtools_page/index.html | 42 -- .../webextensions/manifest.json/icons/index.html | 79 ---- .../add-ons/webextensions/manifest.json/index.html | 132 ------ .../webextensions/match_patterns/index.html | 431 ------------------- .../mozilla/add-ons/webextensions/tips/index.html | 50 --- .../user_interface/browser_action/index.html | 51 --- .../user_interface/browser_styles/index.html | 454 -------------------- .../user_interface/context_menu_items/index.html | 52 --- .../user_interface/devtools_panels/index.html | 63 --- .../user_interface/extension_pages/index.html | 65 --- .../webextensions/user_interface/index.html | 94 ----- .../user_interface/notifications/index.html | 51 --- .../user_interface/omnibox/index.html | 71 ---- .../user_interface/options_pages/index.html | 65 --- .../user_interface/page_actions/index.html | 51 --- .../webextensions/user_interface/popups/index.html | 61 --- .../user_interface/sidebars/index.html | 58 --- .../what_are_webextensions/index.html | 60 --- .../add-ons/webextensions/what_next_/index.html | 61 --- .../your_first_webextension/index.html | 154 ------- .../your_second_webextension/index.html | 461 --------------------- 41 files changed, 5549 deletions(-) delete mode 100644 files/pt-pt/mozilla/add-ons/index.html delete 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/browseraction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/examples/index.html delete 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/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/tips/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html (limited to 'files/pt-pt/mozilla/add-ons') diff --git a/files/pt-pt/mozilla/add-ons/index.html b/files/pt-pt/mozilla/add-ons/index.html deleted file mode 100644 index 2b69084b27..0000000000 --- a/files/pt-pt/mozilla/add-ons/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Extras (Add-ons) -slug: Mozilla/Add-ons -tags: - - Extensões - - Extras - - Landing - - Mozilla - - extensão -translation_of: Mozilla/Add-ons ---- -
{{AddonSidebar}}
- -

Os extras permitem que os responsáveis pelo desenvolvimento estendam e modifiquem a funcionalidade do Firefox. As mesmas são criadas utilizando as tecnologias da Web padrão - CSS, HTML e JavaScript - mais algumas APIs de JavaScript dedicadas. Entre outras coisas, um extra poderia:

- - - -

Desenvolver extras

- -

Existem, de momento, vários conjuntos de  ferramentas utilizadas para desenvolver Aplicações Complementares mas as  chamadas Extensões da Web vão tornar-se o padrão pelo final de 2017. Das restantes a expectativa é de que se tornem obsoletas dentro do mesmo periodo de tempo.

- -

Neste documento vai encontrar informação sobre as opções disponíveis para desenvolver aplicações complementares para que possa decidir qual a melhor para si agora e no futuro.

- -

Criar um Novo Extra

- -

Se está a desenvolver uma nova aplicação complementar recomendamos que escolha entre um dos dois seguintes métodos. Até que a transição para as Extensões da Web esteja finalizada, existirão prós e contras em relação a ambos os métodos. Por favor leia atentamente as opções para decidir qual a melhor para funcionar com a sua aplicação.

- - - -

Migrar um Extra Existente

- -

There are changes coming to Firefox in the next year that will make browsing more reliable for users, and creating add-ons easier for developers. Your add-on may require updating to maintain its compatibility, but once this is done and the transition is complete, your add-on will be more interoperable, secure, and future-proof than ever.

- -

We've created resources, migration paths, office hours, and more, to ensure you have the support you need to get through the transition.

- -

To get started, use the add-on compatibility checker to see if your add-on will be affected.

- -

Publicação de extras

- -

Addons.mozilla.org, commonly known as "AMO," is Mozilla's official site for developers to list add-ons, and for users to discover them. By uploading your add-on to AMO, you can participate in our community of users and creators, and find an audience for your add-on.

- -

You are not required to list your add-on on AMO, but starting with Firefox 40, your code must be signed by Mozilla or users won't be able to install it.

- -

For an overview of the process of publishing your add-on, see Signing and distributing your add-on.

- -

Outros tipos de extras

- -

Generally, when people speak of add-ons they're referring to extensions, but there are a few other add-on types that allow users to customize Firefox. Those add-ons include:

- - - -
-

Contacte-nos

- -

Pode utilizar as hiperligações abaixo para obetr ajuda, manter-se atualizado com as notícias relacionadas com os complementos, e dar-nos a sua opinião/comentário.

- -

Fórum de extras

- -

Utilize o fórum de conversação sobre os complementos para discutir todos aspetos do desenvolvimento de complementos e obter ajuda.

- -

Listas de endereços/discussão

- -

Use the dev-addons list to discuss development of the add-ons ecosystem, including the development of the WebExtensions system and of AMO:

- - - -

IRC

- -

If you're a fan of IRC, you can get in touch at:

- - 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 deleted file mode 100644 index 3dfff5adde..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Anatomia de uma extensão -slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao ---- -
{{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/browseraction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html deleted file mode 100644 index 2b520684db..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Ação do navegador -slug: Mozilla/Add-ons/WebExtensions/API/browserAction -tags: - - API - - Ação do navegador - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/browserAction ---- -
{{AddonSidebar}}
- -

Adiciona um botão à barra de ferramentas do navegador.

- -

Uma ação do navegador é um botão na barra de ferramentas do navegador.

- -

You can associate a popup with the button. The popup is specified using HTML, CSS and JavaScript, just like a normal web page. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts, but its global context is the popup, not the current page displayed in the browser. To affect web pages you need to communicate with them via messages.

- -

If you specify a popup, it will be shown — and the content will be loaded — when the user clicks the icon. If you do not specify a popup, then when the user clicks the icon an event is dispatched to your extension.

- -

You can define most of a browser action's properties declaratively using the browser_action key in the manifest.json.

- -

With the browserAction API, you can:

- - - -

Tipos

- -
-
{{WebExtAPIRef("browserAction.ColorArray")}}
-
An array of four integers in the range 0-255 defining an RGBA color.
-
{{WebExtAPIRef("browserAction.ImageDataType")}}
-
Pixel data for an image. Must be an ImageData object (for example, from a {{htmlelement("canvas")}} element).
-
- -

Funções

- -
-
{{WebExtAPIRef("browserAction.setTitle()")}}
-
Sets the browser action's title. This will be displayed in a tooltip.
-
{{WebExtAPIRef("browserAction.getTitle()")}}
-
Gets the browser action's title.
-
{{WebExtAPIRef("browserAction.setIcon()")}}
-
Sets the browser action's icon.
-
{{WebExtAPIRef("browserAction.setPopup()")}}
-
Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon.
-
{{WebExtAPIRef("browserAction.getPopup()")}}
-
Gets the HTML document set as the browser action's popup.
-
{{WebExtAPIRef("browserAction.openPopup()")}}
-
Open the browser action's popup.
-
{{WebExtAPIRef("browserAction.setBadgeText()")}}
-
Sets the browser action's badge text. The badge is displayed on top of the icon.
-
{{WebExtAPIRef("browserAction.getBadgeText()")}}
-
Gets the browser action's badge text.
-
{{WebExtAPIRef("browserAction.setBadgeBackgroundColor()")}}
-
Sets the badge's background color.
-
{{WebExtAPIRef("browserAction.getBadgeBackgroundColor()")}}
-
Gets the badge's background color.
-
{{WebExtAPIRef("browserAction.enable()")}}
-
Enables the browser action for a tab. By default, browser actions are enabled for all tabs.
-
{{WebExtAPIRef("browserAction.disable()")}}
-
Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active.
-
- -

Eventos

- -
-
{{WebExtAPIRef("browserAction.onClicked")}}
-
Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
-
- -

Compatibilidade de navegador

- -

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

- - - -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.browserAction API. This documentation is derived from browser_action.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/browsingdata/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html deleted file mode 100644 index 14dbd68d3a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: browsingData -slug: Mozilla/Add-ons/WebExtensions/API/browsingData -tags: - - API - - Add-ons - - Extensions - - NeedsTranslation - - Non-standard - - Reference - - TopicStub - - WebExtensions - - browsingData -translation_of: Mozilla/Add-ons/WebExtensions/API/browsingData ---- -
{{AddonSidebar}}
- -

Enables extensions to clear the data that is accumulated while the user is browsing.

- -

In the browsingData API, browsing data is divided into types:

- - - -

You can use the {{WebExtAPIRef("browsingData.remove()")}} function to remove any combination of these types. There are also dedicated functions to remove each particular type of data, such as {{WebExtAPIRef("browsingData.removePasswords()", "removePasswords()")}}, {{WebExtAPIRef("browsingData.removeHistory()", "removeHistory()")}} and so on.

- -

All the browsingData.remove[X]() functions take a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which you can use to control two further aspects of data removal:

- - - -

Finally, this API gives you a {{WebExtAPIRef("browsingData.settings()")}} function that gives you the current value of the settings for the browser's built-in "Clear History" feature.

- -

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

- -

Types

- -
-
{{WebExtAPIRef("browsingData.DataTypeSet")}}
-
Object used to specify the type of data to remove: for example, history, downloads, passwords, and so on.
-
{{WebExtAPIRef("browsingData.RemovalOptions")}}
-
Object used to specify how far back in time to remove data, and whether to remove data added through normal web browsing, by hosted apps, or by add-ons.
-
- -

Methods

- -
-
{{WebExtAPIRef("browsingData.remove()")}}
-
Removes browsing data for the data types specified.
-
{{WebExtAPIRef("browsingData.removeCache()")}}
-
Clears the browser's cache.
-
{{WebExtAPIRef("browsingData.removeCookies()")}}
-
Removes cookies.
-
{{WebExtAPIRef("browsingData.removeDownloads()")}}
-
Removes the list of downloaded files.
-
{{WebExtAPIRef("browsingData.removeFormData()")}}
-
Clears saved form data.
-
{{WebExtAPIRef("browsingData.removeHistory()")}}
-
Clears the browser's history.
-
{{WebExtAPIRef("browsingData.removeLocalStorage()")}}
-
Clears any local storage created by websites.
-
{{WebExtAPIRef("browsingData.removePasswords()")}}
-
Clears saved passwords.
-
{{WebExtAPIRef("browsingData.removePluginData()")}}
-
Clears data associated with plugins.
-
{{WebExtAPIRef("browsingData.settings()")}}
-
Gets the current value of settings in the browser's "Clear History" feature.
-
- -

Browser compatibility

- - - -

{{Compat("webextensions.api.browsingData", 2)}}

- - - -

{{WebExtExamples("h2")}}

- -
Acknowledgements - -

This API is based on Chromium's chrome.browsingData 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/browsingdata/removeplugindata/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html deleted file mode 100644 index e67f9b8c70..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: browsingData.removePluginData() -slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData -tags: - - API - - Dados de navegação - - Extensões - - Extensões da Web - - Extras - - Referencia - - metodo - - remover Dados do Plug-in -translation_of: Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData ---- -
{{AddonSidebar()}}
- -

Limpa dados guardados nos plug-ins do navegador.

- -

Pode utilizar o parâmetro removalOptions, que é um objeto {{WebExtAPIRef("browsingData.RemovalOptions")}}, para:

- - - -

Esta é uma função assíncrona que retorna um Promise.

- -

Sintaxe

- -
var removing = browser.browsingData.removePluginData(
-  removalOptions            // RemovalOptions object
-)
-
- -

Parâmetros

- -
-
removalOptions
-
object. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only plugin data stored after a given time, and whether to clear only data stored by plugins running in normal web pages or to clear data stored by plugins running in hosted apps and extensions as well.
-
- -

Devolver valor

- -

A Promise that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message.

- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.api.browsingData.removePluginData")}}

- -

Exemplos

- -

Remove data stored by plugins in the last week:

- -
function onRemoved() {
-  console.log("removed");
-}
-
-function onError(error) {
-  console.error(error);
-}
-
-function weekInMilliseconds() {
-  return 1000 * 60 * 60 * 24 * 7;
-}
-
-var oneWeekAgo = (new Date()).getTime() - weekInMilliseconds();
-
-browser.browsingData.removePluginData({since: oneWeekAgo}).
-then(onRemoved, onError);
- -

Remove all data stored by plugins:

- -
function onRemoved() {
-  console.log("removed");
-}
-
-function onError(error) {
-  console.error(error);
-}
-
-browser.browsingData.removePluginData({}).
-then(onRemoved, onError);
- -

{{WebExtExamples}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.browsingData 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 deleted file mode 100644 index 2d7cb8839d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html +++ /dev/null @@ -1,104 +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 -original_slug: 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/i18n/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html deleted file mode 100644 index 824e2eb308..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: i18n -slug: Mozilla/Add-ons/WebExtensions/API/i18n -tags: - - API - - Extensões - - Extensões da Web - - Extras - - Não Padrão - - Referencia - - i18n -translation_of: Mozilla/Add-ons/WebExtensions/API/i18n ---- -
{{AddonSidebar}}
- -

Funções para a internationalizar a sua extensão. Pode utilizar estas APIs para ter as suas strings traduzidas dos ficheiros de localização empacotados com a sua extensão, descubra o idioma atual do navegador e descubra o valor do seu cabeçalho Accept-Language.

- -

Para mais detalhes em como utilizar i18n para sua extensão, consulte:

- - - -

Tipos

- -
-
{{WebExtAPIRef("i18n.LanguageCode")}}
-
A language tag such as "en-US" or "fr".
-
- -

Funções

- -
-
{{WebExtAPIRef("i18n.getAcceptLanguages()")}}
-
Gets the accept-languages of the browser. This is different from the locale used by the browser. To get the locale, use {{WebExtAPIRef('i18n.getUILanguage')}}.
-
{{WebExtAPIRef("i18n.getMessage()")}}
-
Gets the localized string for the specified message.
-
{{WebExtAPIRef("i18n.getUILanguage()")}}
-
Gets the UI language of the browser. This is different from {{WebExtAPIRef('i18n.getAcceptLanguages')}} which returns the preferred user languages.
-
{{WebExtAPIRef("i18n.detectLanguage()")}}
-
Detects the language of the provided text using the Compact Language Detector.
-
- -
-
- -

Compatibilidade de navegador

- -

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

- -

{{WebExtExamples("h2")}}

- -
-
- -
Agradecimentos - -

This API is based on Chromium's chrome.i18n API. This documentation is derived from i18n.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/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/index.html deleted file mode 100644 index 24e8c119a7..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/API -translation_of: Mozilla/Add-ons/WebExtensions/API ---- -
{{AddonSidebar}}
- -
{{SubpagesWithSummaries}}
- -
Agradecimentos - -

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/pageaction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html deleted file mode 100644 index 1453336c6c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Ação de página -slug: Mozilla/Add-ons/WebExtensions/API/pageAction -tags: - - API - - Ação de página - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/pageAction ---- -
{{AddonSidebar}}
- -

Uma ação de página é ícone clicável dentro da barra de endereço do navegador.

- -

 

- -

- -

Pode ouvir cliques no ícone, ou especificar uma janela (popup) que será aberta quando o ícone for clicado.

- -

If you specify a popup, you can define its contents and behavior using HTML, CSS, and JavaScript, just like a normal web page. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts.

- -

You can define most of a page action's properties declaratively using the page_action key in your manifest.json, but can also redefine them programmatically using this API.

- -

Page actions are for actions that are only relevant to particular pages. If your icon should always be available, use a browser action instead.

- -

Tipos

- -
-
{{WebExtAPIRef("pageAction.ImageDataType")}}
-
Dados de píxel para uma imagem.
-
- -

Funções

- -
-
{{WebExtAPIRef("pageAction.show()")}}
-
Shows the page action for a given tab.
-
{{WebExtAPIRef("pageAction.hide()")}}
-
Hides the page action for a given tab.
-
{{WebExtAPIRef("pageAction.setTitle()")}}
-
Sets the page action's title. This is displayed in a tooltip over the page action.
-
{{WebExtAPIRef("pageAction.getTitle()")}}
-
Gets the page action's title.
-
{{WebExtAPIRef("pageAction.setIcon()")}}
-
Sets the page action's icon.
-
{{WebExtAPIRef("pageAction.setPopup()")}}
-
Sets the URL for the page action's popup.
-
{{WebExtAPIRef("pageAction.getPopup()")}}
-
Gets the URL for the page action's popup.
-
{{WebExtAPIRef("pageAction.openPopup()")}}
-
Opens the page action's popup.
-
- -

Eventos

- -
-
{{WebExtAPIRef("pageAction.onClicked")}}
-
Fired when a page action icon is clicked. This event will not fire if the page action has a popup.
-
- -

Compatibilidade de navegador

- -

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

- -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.pageAction API. This documentation is derived from page_action.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/sidebaraction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html deleted file mode 100644 index beb8c1c54f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: sidebarAction -slug: Mozilla/Add-ons/WebExtensions/API/sidebarAction -tags: - - API - - Barra Lateral - - Extensões - - Extensões da Web - - Não Padrão - - Referencia - - sidebarAction -translation_of: Mozilla/Add-ons/WebExtensions/API/sidebarAction ---- -
{{AddonSidebar}}
- -

Obtém e define as propriedades da barra lateral de uma extensão.

- -

Uma barra lateral é um painel que é exibido no lado esquerdo ou direito da janela do navegador, ao lado da página da web. O navegador fornece uma interface do utilizador que permite ao utilizador ver as barras laterais disponíveis no momento e selecionar uma barra lateral para exibir. Utilizando a chave de manifest.json sidebar_action , uma extensão pdoe definir a sua própria barra lateral. Utilizando a API sidebarAction descrita aqui, uma extension pode obter um conjunto de propriedades da barra lateral.

- -

A API sidebarAction é modelada de perto na API {{WebExtAPIRef("browserAction")}}.

- -

A API sidebarAction é baseada na API sidebarAction do Opera. Contudo, note que o seguinte ainda não é suportado: setBadgeText(), getBadgeText(), setBadgeBackgroundColor(), getBadgeBackgroundColor(), onFocus, onBlur.

- -

Tipos

- -
-
{{WebExtAPIRef("sidebarAction.ImageDataType")}}
-
Dados de pixel para uma imagem. Deve ser um objeto  ImageData (por exemplo, de um elemento {{htmlelement("canvas")}}).
-
- -

Funções

- -
-
{{WebExtAPIRef("sidebarAction.setPanel()")}}
-
Define o painel da barra lateral.
-
{{WebExtAPIRef("sidebarAction.getPanel()")}}
-
Obtém o painel da barra lateral.
-
{{WebExtAPIRef("sidebarAction.setTitle()")}}
-
Definie o título da barra lateral. Isto será exibido em qualquer IU fornecida pelo navegador para listar as barras de ferrramentas, tal como um menu.
-
{{WebExtAPIRef("sidebarAction.getTitle()")}}
-
Obtém o título da barra lateral.
-
{{WebExtAPIRef("sidebarAction.setIcon()")}}
-
Define o ícone da barra lateral.
-
{{WebExtAPIRef("sidebarAction.open()")}}
-
Abre a abarra lateral.
-
{{WebExtAPIRef("sidebarAction.close()")}}
-
fecha a barra lateral.
-
{{WebExtAPIRef("sidebarAction.isOpen()")}}
-
Verifica sebarra lateral está ou não aberta.
-
- -

Compatibilidade de navegador

- -

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

- -

Exemplo de extras (add-ons)

- - - -
Reconhecimentos - -

Esta API é baseada na API chrome.sidebarAction do Opera.

- -

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 deleted file mode 100644 index f4551690f3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Armazenamento -slug: Mozilla/Add-ons/WebExtensions/API/storage -tags: - - API - - Armazenamento - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/storage -original_slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento ---- -
{{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/browser_support_for_javascript_apis/index.html b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html deleted file mode 100644 index 4f5f3b176e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Suporte de navegador para as APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs -original_slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript ---- -
{{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 deleted file mode 100644 index 13daea5bbf..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html +++ /dev/null @@ -1,447 +0,0 @@ ---- -title: Scripts de Conteúdo -slug: Mozilla/Add-ons/WebExtensions/Content_scripts -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts -original_slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo ---- -
{{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/examples/index.html b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html deleted file mode 100644 index 9e00250f9f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Exemplos de extensões -slug: Mozilla/Add-ons/WebExtensions/Examples -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Examples -original_slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes ---- -
{{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 deleted file mode 100644 index ac5e8d664e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Extensão das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -original_slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento ---- -
{{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/index.html b/files/pt-pt/mozilla/add-ons/webextensions/index.html deleted file mode 100644 index 4c894e2cf1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Extensões de Navegador -slug: Mozilla/Add-ons/WebExtensions -tags: - - Extensões da Web - - Extras - - Landing -translation_of: Mozilla/Add-ons/WebExtensions ---- -
{{AddonSidebar}}
- -

As extensões podem ampliar e modificar a capacidade de um navegador. As extensões para Firefox são criadas utilizando a API de WebExtensions, um sistema de navegador cruzado para desenvolver extensões. Em grande medida, o sistema é compatível com a API de extensão suportada pelo Google Chrome, Opera e W3C Draft Community Group.

- -

As extensões escritas para estes navegadores irão na maioria dos casos ser executadas no Firefox ou Microsoft Edge com apenas algumas alterações. A API também é totalmente compatível com os multiprocessos do Firefox.

- -

Se tiver ideias ou questões, ou precisar de ajuda para migrar um extra legado para utilizar as APIs de WebExtensions, pode contactar-nos em lista de discussões dev-addons ou #webextensions no IRC

- -
-
-

Começar

- - - -

Conceitos

- - - -

Interface do utilizador

- - - -

Como...

- - - -
    -
- -

Porting

- - - -

Fluxo de trabalho do Firefox

- - -
- -
-

Referência

- -

APIS de JavaScript

- - - -
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/API") }}
- -

id="Manifest_keys">Manifest keys

- - - -
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}
-
-
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 deleted file mode 100644 index fef2c0534f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Interceptar Pedidos HTTP -slug: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests -tags: - - Add-ons - - Como-fazer - - Extensões - - ExtensõesWeb -translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests -original_slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP ---- -
{{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/internationalization/index.html b/files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html deleted file mode 100644 index 4892048ba8..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html +++ /dev/null @@ -1,417 +0,0 @@ ---- -title: Internationalization -slug: Mozilla/Add-ons/WebExtensions/Internationalization -tags: - - Artigo - - Extensões da Web - - Guía - - Internacionalização - - Localização - - Tradução - - i18n - - mensagens predefinidas - - messages.json - - placeholders - - símbolos -translation_of: Mozilla/Add-ons/WebExtensions/Internationalization ---- -
{{AddonSidebar}}
- -

A API das Extensões da Web tem um módulo bastante útil disponível para a internacionalização das extensões — i18n. Neste artigo, nós iremos explorar as suas funcionaldiades e fornecemos um exemplo prático de como este funciona. O sistema i18n para as extensões criadas utilizando as APIs da Extensão  da Web é semelhante às bibliotecas de JavaScript comuns do i18n, tal como  i18n.js.

- -
-

The example extension featured in this article — notify-link-clicks-i18n — is available on GitHub. Follow along with the source code as you go through the sections below.

-
- -

Anatomia de uma extensão internacionalizada

- -

An internationalized extension can contain the same features as any other extension — background scripts, content scripts, etc. — but it also has some extra parts to allow it to switch between different locales. These are summarized in the following directory tree:

- - - -

Let's explore each of the new features in turn — each of the below sections represents a step to follow when internationalizing your extension.

- -

Fornecer strings traduzidas em _locales

- -
-
You can look up language subtags using the Find tool on the Language subtag lookup page. Note that you need to search for the English name of the language.
-
- -

Every i18n system requires the provision of strings translated into all the different locales you want to support. In extensions, these are contained within a directory called _locales, placed inside the extension root. Each individual locale has its strings (referred to as messages) contained within a file called messages.json, which is placed inside a subdirectory of _locales, named using the language subtag for that locale's language.

- -

Note that if the subtag includes a basic language plus a regional variant, then the language and variant are conventionally separated using a hyphen: for example, "en-US". However, in the directories under _locales, the separator must be an underscore: "en_US".

- -

So for example, in our sample app we have directories for "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese). Each one of these has a messages.json file inside it.

- -

Let's now look at the structure of one of these files (_locales/en/messages.json):

- -
{
-  "extensionName": {
-    "message": "Notify link clicks i18n",
-    "description": "Name of the extension."
-  },
-
-  "extensionDescription": {
-    "message": "Shows a notification when the user clicks on links.",
-    "description": "Description of the extension."
-  },
-
-  "notificationTitle": {
-    "message": "Click notification",
-    "description": "Title of the click notification."
-  },
-
-  "notificationContent": {
-    "message": "You clicked $URL$.",
-    "description": "Tells the user which link they clicked.",
-    "placeholders": {
-      "url" : {
-        "content" : "$1",
-        "example" : "https://developer.mozilla.org"
-      }
-    }
-  }
-}
- -

This file is standard JSON — each one of its members is an object with a name, which contains a message and a description. All of these items are strings; $URL$ is a placeholder, which is replaced with a substring at the time the notificationContent member is called by the extension. You'll learn how to do this in the {{anch("Retrieving message strings from JavaScript")}} section.

- -
-

Note: You can find much more information about the contents of messages.json files in our Locale-Specific Message reference.

-
- -

Internacionalizar manifest.json

- -

There are a couple of different tasks to carry out to internationalize your manifest.json.

- -

Obter as strings traduzidas em manifests

- -

Your manifest.json includes strings that are displayed to the user, such as the extension's name and description. If you internationalize these strings and put the appropriate translations of them in messages.json, then the correct translation of the string will be displayed to the user, based on the current locale, like so.

- -

To internationalize strings, specify them like this:

- -
"name": "__MSG_extensionName__",
-"description": "__MSG_extensionDescription__",
- -

Here, we are retrieving message strings dependant on the browser's locale, rather than just including static strings.

- -

To call a message string like this, you need to specify it like this:

- -
    -
  1. Two underscores, followed by
  2. -
  3. The string "MSG", followed by
  4. -
  5. One underscore, followed by
  6. -
  7. The name of the message you want to call as defined in messages.json, followed by
  8. -
  9. Two underscores
  10. -
- -
__MSG_ + messageName + __
- -

Especificar uma locale predefinida

- -

Another field you should specify in your manifest.json is default_locale:

- -
"default_locale": "en"
- -

This specifies a default locale to use if the extension doesn't include a localized string for the browser's current locale. Any message strings that are not available in the browser locale are taken from the default locale instead. There are some more details to be aware of in terms of how the browser selects strings — see {{anch("Localized string selection")}}.

- -

Locale-dependent CSS

- -

Note that you can also retrieve localized strings from CSS files in the extension. For example, you might want to construct a locale-dependent CSS rule, like this:

- -
header {
-  background-image: url(../images/__MSG_extensionName__/header.png);
-}
- -

This is useful, although you might be better off handling such a situation using {{anch("Predefined messages")}}.

- -

Obter strings a partir de JavaScript

- -

So, you've got your message strings set up, and your manifest. Now you just need to start calling your message strings from JavaScript so your extension can talk the right language as much as possible. The actual i18n API is pretty simple, containing just four main methods:

- - - -

In our notify-link-clicks-i18n example, the background script contains the following lines:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
- -

The first one just retrieves the notificationTitle message field from the available messages.json file most appropriate for the browser's current locale. The second one is similar, but it is being passed a URL as a second parameter. What gives? This is how you specify the content to replace the $URL$ placeholder we see in the notificationContent message field:

- -
"notificationContent": {
-  "message": "You clicked $URL$.",
-  "description": "Tells the user which link they clicked.",
-  "placeholders": {
-    "url" : {
-      "content" : "$1",
-      "example" : "https://developer.mozilla.org"
-    }
-  }
-}
-
- -

The "placeholders" member defines all the placeholders, and where they are retrieved from. The "url" placeholder specifies that its content is taken from $1, which is the first value given inside the second parameter of getMessage(). Since the placeholder is called "url", we use $URL$ to call it inside the actual message string (so for "name" you'd use $NAME$, etc.) If you have multiple placeholders, you can provide them inside an array that is given to {{WebExtAPIRef("i18n.getMessage()")}} as the second parameter — [a, b, c] will be available as $1, $2, and $3, and so on, inside messages.json.

- -

Let's run through an example: the original notificationContent message string in the en/messages.json file is

- -
You clicked $URL$.
- -

Let's say the link clicked on points to https://developer.mozilla.org. After the {{WebExtAPIRef("i18n.getMessage()")}} call, the contents of the second parameter are made available in messages.json as $1, which replaces the $URL$ placeholder as defined in the "url" placeholder. So the final message string is

- -
You clicked https://developer.mozilla.org.
- -

Direct placeholder usage

- -

It is possible to insert your variables ($1, $2, $3, etc.) directly into the message strings, for example we could rewrite the above "notificationContent" member like this:

- -
"notificationContent": {
-  "message": "You clicked $1.",
-  "description": "Tells the user which link they clicked."
-}
- -

This may seem quicker and less complex, but the other way (using "placeholders") is seen as best practice. This is because having the placeholder name (e.g. "url") and example helps you to remember what the placeholder is for — a week after you write your code, you'll probably forget what $1$8 refer to, but you'll be more likely to know what your placeholder names refer to.

- -

Hardcoded substitution

- -

It is also possible to include hardcoded strings in placeholders, so that the same value is used every time, instead of getting the value from a variable in your code. For example:

- -
"mdn_banner": {
-  "message": "For more information on web technologies, go to $MDN$.",
-  "description": "Tell the user about MDN",
-  "placeholders": {
-    "mdn": {
-      "content": "https://developer.mozilla.org/"
-    }
-  }
-}
- -

In this case we are just hardcoding the placeholder content, rather than getting it from a variable value like $1. This can sometimes be useful when your message file is very complex, and you want to split up different values to make the strings more readable in the file, plus then these values could be accessed programmatically.

- -

In addition, you can use such substitutions to specify parts of the string that you don't want to be translated, such as person or business names.

- -

Seleção de string traduzida

- -

Locales can be specified using only a language code, like fr or en, or they may be further qualified with a region code, like en_US or en_GB, which describes a regional variant of the same basic language. When you ask the i18n system for a string, it will select a string using the following algorithm:

- -
    -
  1. if there is a messages.json file for the exact current locale, and it contains the string, return it.
  2. -
  3. Otherwise, if the current locale is qualified with a region (e.g. en_US) and there is a messages.json file for the regionless version of that locale (e.g. en), and that file contains the string, return it.
  4. -
  5. Otherwise, if there is a messages.json file for the default_locale defined in the manifest.json, and it contains the string, return it.
  6. -
  7. Otherwise return an empty string.
  8. -
- -

Take the following example:

- - - -

Suppose the default_locale is set to fr, and the browser's current locale is en_GB:

- - - -

Mensagens predefinidas

- -

The i18n module provides us with some predefined messages, which we can call in the same way as we saw earlier in {{anch("Calling message strings from manifests and extension CSS")}}. For example:

- -
__MSG_extensionName__
- -

Predefined messages use exactly the same syntax, except with @@ before the message name, for example

- -
__MSG_@@ui_locale__
- -

The following table shows the different available predefined messages:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da mensagemDescrição
@@extension_id -

The extension's internally-generated UUID. You might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message.

- -

You can't use this message in a manifest file.

- -

Also note that this ID is not the add-on ID returned by {{WebExtAPIRef("runtime.id")}}, and that can be set using the applications key in manifest.json. It's the generated UUID that appears in the add-on's URL. This means that you can't use this value as the extensionId parameter to {{WebExtAPIRef("runtime.sendMessage()")}}, and can't use it to check against the id property of a {{WebExtAPIRef("runtime.MessageSender")}} object.

-
@@ui_localeThe current locale; you might use this string to construct locale-specific URLs.
@@bidi_dirThe text direction for the current locale, either "ltr" for left-to-right languages such as English or "rtl" for right-to-left languages such as Arabic.
@@bidi_reversed_dirIf the @@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr".
@@bidi_start_edgeIf the @@bidi_dir is "ltr", then this is "left"; otherwise, it's "right".
@@bidi_end_edgeIf the @@bidi_dir is "ltr", then this is "right"; otherwise, it's "left".
- -

Going back to our earlier example, it would make more sense to write it like this:

- -
header {
-  background-image: url(../images/__MSG_@@ui_locale__/header.png);
-}
- -

Now we can just store our local specific images in directories that match the different locales we are supporting — en, de, etc. — which makes a lot more sense.

- -

Let's look at an example of using @@bidi_* messages in a CSS file:

- -
body {
-  direction: __MSG_@@bidi_dir__;
-}
-
-div#header {
-  margin-bottom: 1.05em;
-  overflow: hidden;
-  padding-bottom: 1.5em;
-  padding-__MSG_@@bidi_start_edge__: 0;
-  padding-__MSG_@@bidi_end_edge__: 1.5em;
-  position: relative;
-}
- -

For left-to-right languages such as English, the CSS declarations involving the predefined messages above would translate to the following final code lines:

- -
direction: ltr;
-padding-left: 0;
-padding-right: 1.5em;
-
- -

For a right-to-left language like Arabic, you'd get:

- -
direction: rtl;
-padding-right: 0;
-padding-left: 1.5em;
- -

Testar a sua extensão

- -

Starting in Firefox 45, you can install extensions temporarily from disk — see Loading from disk. Do this, and then try testing out our notify-link-clicks-i18n extension. Go to one of your favourite websites and click a link to see if a notification appears reporting the URL of the clicked link.

- -

Next, change Firefox's locale to one supported in the extension that you want to test.

- -
    -
  1. Open "about:config" in Firefox, and search for the intl.locale.requested preference (bear in mind that before Firefox 59, this pref is called general.useragent.locale).
  2. -
  3. If the preference exists, double-click it (or press Return/Enter) to select it, enter the language code for the locale you want to test, then click "OK" (or press Return/Enter). For example in our example extension, "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese) are supported. You can also set the value to an empty string (""), which will cause the browser to use the OS default locale.
  4. -
  5. If the intl.locale.requested preference does not exist, right-click the list of preferences (or activate the context menu using the keyboard), and choose "New" followed by "String". Enter intl.locale.requested for the preference name and, "de", or "nl", etc. for the preference value, as described in step 2 above.
  6. -
  7. Search for intl.locale.matchOS and, if the preference exists and has the value true, double-click it  so that it is set to false.
  8. -
  9. Restart your browser to complete the change.
  10. -
- -
-

Nota: This works to change the browser's locale, even if you haven't got the language pack installed for that language. You'll just get the browser UI in your default language if this is the case.

-
- -
    -
- -
-

Nota: To change the result of getUILanguage the language pack is required, since it reflects the browser UI language and not the language used for extension messages.

-
- -

Load the extension temporarily from disk again, then test your new locale:

- - - -

{{EmbedYouTube("R7--fp5pPGg")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html deleted file mode 100644 index 41b720af8b..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: browser_action -slug: Mozilla/Add-ons/WebExtensions/manifest.json/browser_action -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/browser_action ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObjeto
ObrigatórioNão
Exemplo -
-"browser_action": {
-  "browser_style": true,
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  },
-  "default_title": "Whereami?",
-  "default_popup": "popup/geo.html",
-  "theme_icons": [{
-    "light": "icons/geo-32-light.png",
-    "dark": "icons/geo-32.png",
-    "size": 32
-  }]
-}
-
- -

A browser action is a button that your extension adds to the browser's toolbar. The button has an icon, and may optionally have a popup whose content is specified using HTML, CSS, and JavaScript.

- -

If you supply a popup, then the popup is opened when the user clicks the button, and your JavaScript running in the popup can handle the user's interaction with it. If you don't supply a popup, then a click event is dispatched to your extension's background scripts when the user clicks the button.

- -

You can also create and manipulate browser actions programmatically using the browserAction API.

- -

Sintaxe

- -

The browser_action key is an object that may have any of the following properties, all optional:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomeTipoDescrição
browser_styleBooliano -
Novo no Firefox 48
- -

Optional, defaulting to false.

- -

Use this to include a stylesheet in your popup that will make it look consistent with the browser's UI and with other extensions that use the browser_style property. Although this key defaults to false, it's recommended that you include it and set it to true.

- -

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css, or chrome://browser/content/extension-mac.css on OS X.

- -

The Firefox Style Guide describes the classes you can apply to elements in the popup in order to get particular styles.

- -

The latest-download example extension uses browser_style in its popup.

-
default_areaString -
Novo no Firefox 54
- -

Defines the part of the browser in which the button is initially placed. This is a string that may take one of four values:

- -
    -
  • "navbar": the button is placed in the main browser toolbar, alongside the URL bar.
  • -
  • "menupanel": the button is placed in a popup panel.
  • -
  • "tabstrip": the button is placed in the toolbar that contains browser tabs.
  • -
  • "personaltoolbar": the button is placed in the bookmarks toolbar.
  • -
- -

This property is only supported in Firefox.

- -

This property is optional, and defaults to "navbar".

- -

An extension can't change the location of the button after it has been installed, but the user may be able to move the button using the browser's built-in UI customization mechanism.

-
default_iconObject or String -

Use this to specify one or more icons for the browser action. The icon is shown in the browser toolbar by default.

- -

Icons are specified as URLs relative to the manifest.json file itself.

- -

You can specify a single icon file by supplying a string here:

- -
-"default_icon": "path/to/geo.svg"
- -

To specify multiple icons in different sizes, specify an object here. The name of each property is the icon's height in pixels, and must be convertible to an integer. The value is the URL. For example:

- -
-    "default_icon": {
-      "16": "path/to/geo-16.png",
-      "32": "path/to/geo-32.png"
-    }
- -

See Choosing icon sizes for more guidance on this.

-
default_popupString -

The path to an HTML file containing the specification of the popup.

- -

The HTML file may include CSS and JavaScript files using <link> and <script> elements, just like a normal web page.

- -

Unlike a normal web page, JavaScript running in the popup can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions).

- -

This is a localizable property.

-
default_titleString -

Tooltip for the button, displayed when the user moves their mouse over it. If the button is added to the browser's menu panel, this is also shown under the app icon.

- -

This is a localizable property.

-
theme_iconsArray -

This property enables you to specify different icons for dark and light themes.

- -

If this property is present, it's an array containing at least one ThemeIcons object. A ThemeIcons object contains three properties, all mandatory:

- -
-
"dark"
-
A URL pointing to an icon. This icon will be selected when themes with dark text are active (e.g. Firefox's Light theme, and the Default theme if no default_icon is specified).
-
"light"
-
A URL pointing to an icon. This icon will be selected when themes with light text are active (e.g. Firefox's Dark theme).
-
"size"
-
The size of the two icons in pixels.
-
- -

Icons are specified as URLs relative to the manifest.json file itself.

- -

Providing multiple ThemeIcons objects enables you to supply a set of icon pairs in different sizes.

-
- -

Escolher os tamanhos do ícone

- -

The browser action's icon may need to be displayed in different sizes in different contexts:

- - - -

If the browser can't find an icon of the right size in a given situation, it will pick the best match and scale it. Scaling may make the icon appear blurry, so it's important to choose icon sizes carefully.

- -

There are two main approaches to this. You can supply a single icon as an SVG file, and it will be scaled correctly:

- -
"default_icon": "path/to/geo.svg"
- -

Alternatively, you can supply several icons in different sizes, and the browser will pick the best match.

- -

In Firefox:

- - - -

So you can specify icons that match exactly, on both normal and Retina displays, by supplying three icon files, and specifying them like this:

- -
    "default_icon": {
-      "16": "path/to/geo-16.png",
-      "32": "path/to/geo-32.png",
-      "64": "path/to/geo-64.png"
-    }
- -

If Firefox can't find an exact match for the size it wants, then it will pick the smallest icon specified that's bigger than the ideal size. If all icons are smaller than the ideal size, it will pick the biggest icon specified.

- -

Exemplo

- -
"browser_action": {
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  }
-}
- -

A browser action with just an icon, specified in 2 different sizes. The extension's background scripts can receive click events when the user clicks the icon using code like this:

- -
 browser.browserAction.onClicked.addListener(handleClick);
- -
"browser_action": {
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  },
-  "default_title": "Whereami?",
-  "default_popup": "popup/geo.html"
-}
- -

A browser action with an icon, a title, and a popup. The popup will be shown when the user clicks the button.

- -

For a simple, but complete, extension that uses a browser action, see the walkthrough tutorial.

- -

Compatibilidade de navegador

- -

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html deleted file mode 100644 index 3d52790362..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: applications -slug: Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObject
ObrigatórioUsually, no (but see also When do you need an Add-on ID?). Mandatory before Firefox 48 (desktop) and Firefox for Android.
Exemplo -
-"applications": {
-  "gecko": {
-    "id": "addon@example.com",
-    "strict_min_version": "42.0"
-  }
-}
-
- -

Descrição

- -

A chave applications contém chaves que são especificas de uma application de um anfitrião em particular.

- -

Propriedadee (Gecko) do Firefox

- -

Currently this contains just one key, gecko, which may contain four string attributes:

- - - -

Consulte a lista das versões válidas de Gecko.

- -

Formato da Id. da Extensão

- -

A Id. da extensão deve ser uma das seguintes:

- - - -

The latter format is easier to generate and manipulate. Be aware that using a real email address here may attract spam.

- -

Por exemplo:

- -
"id": "extensionname@example.org",
-
-"id": "{daf44bf7-a45e-4450-979c-91cf07434c3d}"
- -

Propriedades do Microsoft Edge

- -

Microsoft Edge stores its browser specific settings in the edge subkey, which has the following properties:

- -
-
browser_action_next_to_addressbar
-
-

Boolean property which controls the placement of the browser action.

- - -
-
- -

Exemplos

- -

Example with all possible keys. Note that most extensions will omit strict_max_version and update_url.

- -
"applications": {
-  "gecko": {
-    "id": "addon@example.com",
-    "strict_min_version": "42.0",
-    "strict_max_version": "50.*",
-    "update_url": "https://example.com/updates.json"
-  },
-  "edge": {
-    "browser_action_next_to_addressbar": true
-  }
-}
- -

Compatibilidade de navegador

- - - -

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

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html deleted file mode 100644 index 6f53c96b01..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: devtools_page -slug: Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoString
ObrigatórioNão
Exemplo -
-"devtools_page": "devtools/my-page.html"
-
- -

Utilziae esta chave para permitir que a sua extensão amplie as devtools do navegador integradas.

- -

esta chave é definida como um URL para um ficheiro HTML. O ficheiro HTML deverá ser incorporado com a extensão, e o URL é relativo à raiz das extensões.

- -

Consulte Extensão das ferramentas de desenvolvimento para saber mais.

- -

Exemplo

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

Compatibilidade de navegador

- - - -

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

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 deleted file mode 100644 index 66eb369f78..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Ícones (icons) -slug: Mozilla/Add-ons/WebExtensions/manifest.json/icons -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons -original_slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones ---- -
{{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/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html deleted file mode 100644 index 4f8e087281..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: manifest.json -slug: Mozilla/Add-ons/WebExtensions/manifest.json -tags: - - Add-ons - - Extensões - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json ---- -
{{AddonSidebar}}
- -

O ficheiro manifest.json é o único ficheiro que deve ser incluído em extensões que usem APIs de WebExtension.

- -

Com o manifest.json, é possível especificar metadados sobre a extensão a que pertence, tal como o nome, a versão, e funcionalidades como scripts de background, scripts de conteúdo, e ações de browser.

- -

O manifest.json é um ficheiro em formato JSON, mas também suporta comentários do tipo "//".

- -

Propriedades do manifest.json

- -

Seguem-se as propriedades que o manifest.json suporta:

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

Notas sobre propriedades do manifest.json

- - - -

Como aceder a propriedades manifest.json em runtime

- -

É possível aceder ao manifest.json de uma extensão a partir de um script da mesma, com a função de JavaScript {{WebExtAPIRef("runtime.getManifest()")}}:

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

Compatibilidade de browsers

- -

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

- -

Exemplo

- -

Os exemplos seguintes demonstram como funcionam algumas propriedades comuns nos manifest.json.  

- -
-

Nota: Estes exemplos não funcionam se forem simplesmente copiados e colados. As propriedades necessárias são determinadas pelas características de cada extensão

-
- -

Para ver exemplos completos de extensões, veja a página Exemplos de extensões.

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

Compatibilidade de browsers

- -

Consulte a tabela de compatibilidade de browsers do manifest.json para saber que browsers suportam cada propriedade do manifest.json.

- -

Ver também

- -

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

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 deleted file mode 100644 index e7330b3010..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html +++ /dev/null @@ -1,431 +0,0 @@ ---- -title: dubla padrões em extensão manifestos -slug: Mozilla/Add-ons/WebExtensions/Match_patterns -translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns -original_slug: Mozilla/Add-ons/WebExtensions/dubla_padrões ---- -
{{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/tips/index.html b/files/pt-pt/mozilla/add-ons/webextensions/tips/index.html deleted file mode 100644 index dd02a81c1d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/tips/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Tips and Tricks -slug: Mozilla/Add-ons/WebExtensions/Tips -translation_of: Mozilla/Add-ons/WebExtensions/Tips ---- -

{{AddonSidebar}}

- -

Esta paginas contêm varias dicas e truques que deve ser útil para muitas pessoas devenvolvendo extensões usando WebExtension APIs.

- -

Usando recursos avancados do ECMAScript 2015 e 2016.

- -

Firefox suporta muitos recursos do ECMAScript 2015 fora da box. Diversas novidades e recursos experimental, contanto entretanto, não estão disponiveis por padrão para a Web ou WebExtensions. Se você quer usar esses recursos,  é melhor transpilar seu codigo usando uma ferramenta como o Babel.

- -

Cuidado que qualquer coisa abalixo desta linha é informação desatualizada e tem sido removida do Babel 6.

- -

Babel fornece transformações para a grande maioria dos recursos do ES2015, e os habilita por padrão. Uma vez que o Firefox já suporta totalmente a maiorias dessas, é melhor configurar Babel para ignorar-lá. Nós sugerimos criando um arquivo .babelrc, ou uma seção babel em seu arquivo de projeto package.json contendo o seguinte:

- -
{
-  "env": {
-    "firefox": {
-      "sourceMaps": "inline",
-      "blacklist": [
-        "es5.properties.mutators",
-        "es6.arrowFunctions",
-        "es6.destructuring",
-        "es6.forOf",
-        "es6.parameters",
-        "es6.properties.computed",
-        "es6.properties.shorthand",
-        "es6.spec.symbols",
-        "es6.spread",
-        "es6.tailCall",
-        "es6.templateLiterals",
-        "es6.regex.sticky",
-        "es6.regex.unicode"
-      ]
-    }
-  }
-}
-
- -

Então, para compilar um script individual simplesmente, execute:

- -
BABEL_ENV=firefox babel <filename>
-
- -

Ou, para compilar cada arquivo JavaScript dentro do diretório src e colocar os arquivos compilados em compiled, copiando arquivos não-JavaScript no processo, executadno:

- -
BABEL_ENV=firefox babel -Dd compiled src
-
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 deleted file mode 100644 index 421dffbb28..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Botão da Barra de Ferramentas -slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action -tags: - - Extensão da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador ---- -
{{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 deleted file mode 100644 index 233cf4ff31..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html +++ /dev/null @@ -1,454 +0,0 @@ ---- -title: Estilos de navegador -slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador ---- -
{{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 deleted file mode 100644 index bf69421558..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Itens do menu de contexto -slug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items -original_slug: >- - Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto ---- -
{{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 deleted file mode 100644 index ffd1b942af..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Painéis das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels -tags: - - Extensões da Web - - Guía - - Interface do Utilizador - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/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 deleted file mode 100644 index bea67ee60c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Páginas de extensão -slug: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão ---- -
{{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 deleted file mode 100644 index b18f1afd85..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Interface do utilizador -slug: Mozilla/Add-ons/WebExtensions/user_interface -tags: - - Interface do Utilizador - - Landing - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/user_interface -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador ---- -
{{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 deleted file mode 100644 index 8c8c113425..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Notificações -slug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes ---- -
{{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 deleted file mode 100644 index 2470a05c32..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Sugestões da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/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 deleted file mode 100644 index d3a560412f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Página de opções -slug: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/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 deleted file mode 100644 index 57407bc175..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Botão da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina ---- -
{{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 deleted file mode 100644 index 7d7c1d469e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Janelas (Popups) -slug: Mozilla/Add-ons/WebExtensions/user_interface/Popups -tags: - - Extensions - - IU - - Interface do Utilizador - - Janela - - popup -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/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 deleted file mode 100644 index 02509b9229..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Barras laterais -slug: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais ---- -
{{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 deleted file mode 100644 index ada2698b44..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: O que são extensões? -slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions -tags: - - Extensões - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions -original_slug: Mozilla/Add-ons/WebExtensions/O_que_sao_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 deleted file mode 100644 index c4ac2a8348..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: E a seguir? -slug: Mozilla/Add-ons/WebExtensions/What_next_ -tags: - - Extensão da Web - - Extensões - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/What_next_ -original_slug: Mozilla/Add-ons/WebExtensions/E_a_seguir ---- -
{{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 deleted file mode 100644 index 2b711124ca..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: A sua primeira extensão -slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension -tags: - - Extensões da Web - - Guía -translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao ---- -
{{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 deleted file mode 100644 index 9d3c22efac..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html +++ /dev/null @@ -1,461 +0,0 @@ ---- -title: A sua segunda extensão -slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao ---- -
{{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