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 --------------- files/pt-pt/mozilla/firefox/index.html | 73 --- .../pt-pt/mozilla/firefox/releases/1.5/index.html | 26 - files/pt-pt/mozilla/firefox/releases/2/index.html | 94 --- .../pt-pt/mozilla/firefox/releases/3.5/index.html | 261 -------- .../releases/3.5/updating_extensions/index.html | 112 ---- .../pt-pt/mozilla/firefox/releases/3.6/index.html | 310 ---------- files/pt-pt/mozilla/firefox/releases/3/index.html | 298 ---------- .../releases/3/site_compatibility/index.html | 78 --- .../releases/3/updating_extensions/index.html | 210 ------- files/pt-pt/mozilla/firefox/releases/4/index.html | 657 --------------------- files/pt-pt/mozilla/firefox/releases/5/index.html | 114 ---- files/pt-pt/mozilla/firefox/releases/6/index.html | 250 -------- files/pt-pt/mozilla/firefox/releases/70/index.html | 140 ----- files/pt-pt/mozilla/firefox/releases/index.html | 25 - files/pt-pt/mozilla/index.html | 16 - 56 files changed, 8213 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 delete mode 100644 files/pt-pt/mozilla/firefox/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/1.5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/2/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.6/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/4/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/6/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/70/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/index.html delete mode 100644 files/pt-pt/mozilla/index.html (limited to 'files/pt-pt/mozilla') 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
-
diff --git a/files/pt-pt/mozilla/firefox/index.html b/files/pt-pt/mozilla/firefox/index.html deleted file mode 100644 index 2e57b0d4f0..0000000000 --- a/files/pt-pt/mozilla/firefox/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Firefox -slug: Mozilla/Firefox -tags: - - Firefox - - Landing - - Mozilla -translation_of: Mozilla/Firefox ---- -
{{FirefoxSidebar}}
- -

Firefox é o navegador popular da Web da Mozilla, disponível para múltiplas plataformas, incluindo Linux, OS X e Windows para PC e em todos os dispositivos móveis Android e iOS. Com ampla compatibilidade, as tecnologias da Web mais recentes, e ferramentas de programação poderosas, o Firefox é uma excelente escolha, tanto para os programadores da Web como para os utilizadores finais.

- -

O Firefox é um projeto de código aberto; a maior parte do código é fornecido pela nossa comunidade enorme de voluntários. Aqui pode aprender sobre como contribuir para o projeto Firefox e irá encontrar também hiperligações para informação sobre a criação de Extras do Firefox, utilizando as ferramentas de programador no Firefox, e outros tópicos.

- -
-

Aprenda a criar Extras para o Firefox, como desenvolver e criar o próprio Firefox, e como os internos do Firefox e os respetivos subprojetos funcionam.

-
- - - -

Canais do Firefox

- -

O Firefox está disponível em cinco canais.

- -

Firefox Nightly

- -

Todas as noites nós contruimos o Firefox a partir do último código disponível em mozilla-central. Estas configurações destinam-se aos programadores do Firefox ou para aqueles que desejam experimentar as últimas funcionalidades inovadoras enquanto estas estão ainda em fase de desenvolvimento.

- -

Transferir Firefox Nightly

- -

Edição do Programador do Firefox

- -

Esta é uma versão do Firefox personalizada para programadores. A cada seis semanas, nós selecionamos as funcionalidades do Firefox Nightly que estão estáveis o suficiente e criamos uma nova versão da Edição do Programador do Firefox. Nós adicionamos também algumas funcionalidades extra para programadores, que estão apenas disponíveis neste canal.

- -

Saiba mais acerca da Edição do Programador do Firefox.

- -

Transferir Firefox Developer Edition

- -

Firefox Beta

- -

Após utilizar a Edição do Programador do Firefox por seis semanas, nós selecionamos as funcionalidades que estão estáveis o suficiente e criamos uma nova versão do Firefox Beta. As configurações do Firefox Beta destinam-se a entusiastas do Firefox para testar as funcionalidades destinadas a serem lançadas na próxima versão do Firefox.

- -

Transferir Firefox Beta

- -

Firefox

- -

Após estabilizar para outras seis semanas com a versão Beta, nós estamos prontos para lançar as novas funcionalidades para milhões de utilizadores numa nova versão de lançamento do Firefox.

- -

Transferir Firefox

- -

Firefox Extended Support Release (ESR)

- -

Firefox ESR is the long-term support edition of Firefox for desktop for use by organizations including schools, universities, businesses and others who need extended support for mass deployments.

- -

Learn more about Firefox Extended Support Release.

- -

Transferir Firefox ESR

- -

Perfis do Firefox

- -

If you find yourself using multiple Firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple Firefox profiles by turning Firefox's Profile Manager and other profile management tools to your advantage.

diff --git a/files/pt-pt/mozilla/firefox/releases/1.5/index.html b/files/pt-pt/mozilla/firefox/releases/1.5/index.html deleted file mode 100644 index 29dab49ca6..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/1.5/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Firefox 1.5 para Desenvolvedores -slug: Mozilla/Firefox/Releases/1.5 -translation_of: Mozilla/Firefox/Releases/1.5 -original_slug: Firefox_1.5_para_Desenvolvedores ---- -
{{FirefoxSidebar}}

 

- -

Firefox 1.5

- -

Como o primeiro lançamento no ciclo de desenvolvimento de produto Firefox 1.5 dedicada a desenvolvedores web e autores de Extensões para teste de compatibilidade, Firefox 1.5, baseado no motor Gecko 1.8, melhora o já melhor na classe suporte de normas e providencia novas capacidades para suportar a próxima geração de aplicações web. Firefox 1.5 tem como características, melhor suporte para CSS 2 e CSS 3, APIs para gráficos 2D com scripts e programáveis com SVG 1.1 e <canvas>, XForms e eventos XML, e satisfatórios realces em DHTML, JavaScript e DOM.

- -

Firefox 1.5 está disponível para o download em: http://www.mozilla.com/firefox/

- -

Ferramentas para Desenvolvedores

- -

Diversas ferramentas e extensões do browser estão disponíveis para ajudar no suporte do Firefox 1.5 aos desenvolvedores.

- - - -

Nota: Algumas extensões não suportam atualmente o Firefox 1.5 e serão desabilitadas automaticamente.

diff --git a/files/pt-pt/mozilla/firefox/releases/2/index.html b/files/pt-pt/mozilla/firefox/releases/2/index.html deleted file mode 100644 index 3ba2adba19..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/2/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Firefox 2 para desenvolvedores -slug: Mozilla/Firefox/Releases/2 -translation_of: Mozilla/Firefox/Releases/2 -original_slug: Firefox_2_para_desenvolvedores ---- -
{{FirefoxSidebar}}

Novas características para desenvolvedores no Firefox 2

- -

Firefox 2 introduz uma vasta gama de características e potencialidades novas.

- -

Se não houver um link para algum título abaixo, é um título provisório do MDC até que o artigo esteja escrito.

- -

Para desenvolvedores de aplicações e web sites

- -
-
Microsummaries
-
Microsummaries são uma nova maneira de web sites fornecerem material de referência rápida para usuários. Páginas onde existe um gerador de microsummary podem ser adicionadas à barra de favoritos com conteúdo que atualiza periodicamente baseado na especificação microsummary.
-
- -
-
Creating a Microsummary
-
Um tutorial sobre como criar um gerador microsummary.
-
- -
-
Creating MozSearch plugins
-
Firefox 2 suporta MozSearch, um formato plugin de pesquisa baseado no OpenSearch.
-
- -
-
OpenSearch support in Firefox
-
Firefox 2 suporta também o formato Amazon A9's OpenSearch para plugins de pesquisa.
-
- -
-
Supporting search suggestions in search plugins
-
Como fazer seu plugin MozSearch suportar sugestões de pesquisa, que aparecem em uma caixa popup ao digitar na barra da busca.
-
- -
-
New in JavaScript 1.7
-
Firefox 2 suporta JavaScript 1.7, que possui novas características incluindo let, destructuring assignment, geradores e iteradores, e array comprehensions.
-
- -
-
WHATWG Client-side session and persistent storage
-
Sessão client-side e armazenamento permanente permitem que aplicações web armazenem dados estruturados no lado do cliente.
-
- -
-
SVG in Firefox
-
Firefox 2 tem suporte à SVG (Scalable Vector Graphics) melhorado, implementando o elemento <textPath> e adicionando suporte a alguns atributos não suportados previamente.
-
- -

Para desenvolvedores de extensões e XUL

- -
-
Session restore API
-
Contribuindo com itens a serem salvos e restaurados através das sessões do Firefox.
-
- -
-
Feed content access API
-
Esta API ainda está sendo revisada; documentação estará disponível em breve.
-
- -
-
SAX support
-
Parser API baseada em eventos de XML.
-
- -
-
Adding search engines from web pages
-
Código Javascript pode instruir Firefox a instalar novos plugins de pesquisa escritos com o formato OpenSearch ou Sherlock.
-
- -
-
Adding phishing protection data providers
-
É possível realçar a proteção phishing? do Firefox adicionando fornecedores adicionais de dados ao sistema de navegação seguraainda não encontrei um bom termo - Leandro o que voce acha - Kay - bom Kay, obrigado. :) Caso queira nos ajudar com outras traduções, entre em contato através da página MDC:Comunidade.
-
- -
-
Storage
-
Firefox 2 introduz o mozStorage, uma arquitetura de base de dados baseada no sqlite.
-
- -
-
Best practices for extension versioning
-
Como usar números de versão para tratar de todas as versões de pré-lançamento do firefox 2.
-
- -

Novas características para usuários finais

- -

Para conhecer as novidades para usuários finais das versões 2.0, visite o br.mozdev.

diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/index.html deleted file mode 100644 index d175b9cc1c..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.5/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Firefox 3.5 para desenvolvedores -slug: Mozilla/Firefox/Releases/3.5 -translation_of: Mozilla/Firefox/Releases/3.5 -original_slug: Firefox_3.5_para_desenvolvedores ---- -
{{FirefoxSidebar}}

O Firefox 3.5 introduz várias funcionalidades novas, bem como suporte adicional e melhorado para uma larga variedade de padrões web. Este artigo oferece uma extensa lista, com links para artigos cobrindo as melhorias mais importantes.

-

Novas funcionalidades para desenvolvedores no Firefox 3.5

-

Para desenvolvedores de web sites e aplicações

-

Suporte a HTML 5

-
-
- Usando áudio e vídeo no Firefox
-
- O Firefox 3.5 adicionou suporte para os elementos de áudio e vídeo do HTML 5.
-
- Recursos offline no Firefox (EN)
-
- O Firefox 3.5 agora suporta totalmente as especificações de recursos offline do HTML 5.
-
- Arrastar e largar (drag and drop) (EN)
-
- As APIs de arrastar e soltar do HTML 5 permitem o suporte para  arrastar e soltar itens dentro e entre web sites. Isto também proporciona uma API simples para uso em extensões e aplicações baseadas no Mozilla.
-
-

Novas funcionalidades do CSS suportadas

-
-
- Suporte a fontes baixáveis
-
- A nova @font-face @rule permite que páginas web proporcionem fontes baixáveis, dessa forma estes sites podem ser renderizados exatamente como o autor da página espera.
-
- Consulta de mídia CSS
-
- O Firefox 3.5 suporta consulta de mídia CSS, que melhora o suporte às folhas de estilo dependentes de mídias.
-
- :before e :after atualizados para o CSS 2.1
-
- Os pseudo-elementos :before e :after foram atualizados para o suporte total do CSS 2.1, adicionando suporte para position, float, list-style-*, e algumas propriedades display.
-
- opacity (en)
-
- A estensão Mozilla -moz-opacity para o CSS foi removida em favor da propriedade padrão opacity.
-
- text-shadow (en)
-
- A propriedade text-shadow, que permite ao conteúdo web especificar efeitos de sombra para aplicar em textos e decorações de texto, agora é suportada.
-
- word-wrap (en)
-
- Esta nova propriedade suportada permite ao conteúdo especificar quando as linhas podem ou não serem quebradas no meio de palavras para prevenir o extravasamento quando uma outra string não-quebrável é muito longa para ocupar uma única linha.
-
- -moz-box-shadow (en)
-
- -moz-border-image (en)
-
- -moz-column-rule (en)
-
- -moz-column-rule-width (en)
-
- -moz-column-rule-style (en)
-
- -moz-column-rule-color (en)
-
- -moz-column-gap (en)
-
- O Firefox 3.5 adicionou suporte para estas extensões Mozilla ao CSS.
-
- O valor de cor -moz-nativehyperlinktext (en)
-
- Este novo valor de cores representa a cor de hiperlink padrão do sistema do usuário.
-
- As novas propriedades -moz-window-shadow (en) e -moz-system-metric(mac-graphite-theme) (en)
-
- Estas novas propriedades CSS foram adicionadas para facilitar as edições de temas.
-
- Novos valores para -moz-appearance (en)
-
- Os valores -moz-win-glass e -moz-mac-unified-toolbar foram adicionados em -moz-appearance.
-
- Usando transformações CSS
-
- O Firefox 3.5 suporta transformações CSS. Veja -moz-transform (en) e -moz-transform-origin (en) para detalhes.
-
- :nth-child (en)
-
- :nth-last-child (en)
-
- :nth-of-type (en)
-
- :nth-last-of-type (en)
-
- :first-of-type (en)
-
- :last-of-type (en)
-
- :only-of-type (en)
-
- Todos estes seletores são agora suportados pelo Firefox 3.5.
-
-

Novas funcionalidades da DOM

-
-
- localStorage
-
- O Firefox 3.5 adiciona suporte para a propriedade localStorage do HTML 5, que proporciona uma maneira para as aplicações web armazenarem dados localmente no computador do cliente.
-
- Using DOM workers (EN)
-
- O Firefox 3.5 suporta que trabalhadores (workers) DOM permitam facilmente o suporte para multi-threading em aplicações web.
-
- Using geolocation (EN)
-
- O Firefox 3.5 suporta a API de Geolocalização (Geolocation API), que permite a aplicações web obterem informações sobre a localização atual dos usuários se um provedor desta informação estiver instalado e habilitado.
-
- Using JSON in Firefox (EN)
-
- O supore para JSON está agora integrado ao DOM.
-
- Locating DOM elements using selectors (EN)
-
- A API de seletores (selectors API) permite consultar um documento para localizar os elementos que combinam com uma regra de seleção dada.
-
- The NodeIterator object (EN)
-
- O objeto NodeIterator proporciona suporte para iteração sobre a lista de nós em uma subárvore DOM.
-
- The MozAfterPaint event (EN)
-
- Este novo evento DOM é enviado após realizar atualizações de pintura em janelas.
-
- The MozMousePixelScroll event (EN)
-
- Este novo evento DOM permite a detecção de eventos de rolagem do mouse baseada em pixels ao invés de eventos de rolagem baseados em linhas.
-
-

Novas funcionalidades JavaScript

-
-
- Object.getPrototypeOf() (EN)
-
- Este novo método retorna o protótipo de um objeto específico.
-
- Novos métodos trim no objeto String
-
- O objeto String (en) tem agora os métodos trim() (en), trimLeft() (en) e trimRight() (en).
-
-

Rede

-
-
- Cross-site access controls for HTTP (EN)
-
- No Firefox 3.5, agora é possível para requisições HTTP, incluindo as feitas por XMLHttpRequest (en), trabalhar através de domínios, se o servidor suportar isso.
-
- Progress events for XMLHttpRequest (EN)
-
- Eventos de progresso agora são oferecidos para permitir que extensões monitorem o progresso de requisições.
-
- Suporte a XMLHttpRequest síncrona melhorado
-
- DOM Timeout e Input Events agora são omitidos durante uma XMLHttpRequest síncrona.
-
- Controlling DNS prefetching (EN)
-
- O Firefox 3.5 proporciona pré-carregamento DNS (DNS prefetching), através do qual realiza a resolução do nome do domínio antes do tempo para links incluídos na página atual, com o objetivo de poupar tempo quando os links forem realmente clicados. Este artigo descreve como você pode modificar seu web site para desabilitar o pré-carregamento, ou para ajustar como o pré-carregamento opera.
-
-

Novas funcionalidades Canvas

-
-
- HTML 5 text API for canvas elements (EN)
-
- Os elementos Canvas agora suportam a API de texto do HTML 5.
-
- Shadow effects in a canvas (EN)
-
- Os efeitos de sombra do Canvas agora são suportados.
-
- atributo moz-opaque
-
- Adicionado o atributo DOM, moz-opaque, que permite ao canvas saber quando a translucidez será um fator ou não. Se o canvas sabe que não há translucidez, a performance de pintura pode ser otimizada.
-
-

Novas funcionalidades SVG

-
-
- Applying SVG effects to HTML content (EN)
-
- Você pode aplicar efeitos SVG ao conteúdo HTML e XHTML; este artigo descreve como.
-
-

Novas funcionalidades - Miscelânea

-
-
- ICC color correction in Firefox (EN)
-
- O Firefox 3.5 agora suporta a correção de cores ICC para imagens marcadas.
-
- O atributo defer é agora suportado no elemento script (EN)
-
- Este atributo indica ao navegador que ele pode optar por continuar a analisar e renderizar a página sem aguardar o término da execução do script.
-
-

Outras melhorias

- -

Para desenvolvedores XUL e de complementos

-

Se você é um desenvolvedor de extensões, você deve começar lendo Atualizando extensões para o Firefox 3.5, que oferece um panorama útil de mudanças que podem afetar a sua extensão.

-

Novos componentes e funcionalidades

-
-
- Supporting private browsing mode (EN)
-
- O Firefox 3.5 oferece o modo de Navegação Privada, que não grava as atividades do usuário. Extensões podem suportar a navegação privada seguindo as orientações oferecidas por este artigo.
-
- Security changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à segurança no Firefox 3.5.
-
- Theme changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à temas no Firefox 3.5.
-
- Monitoring WiFi access points (EN)
-
- Código com privilégios UniversalXPConnect agora podem monitorar a lista dos pontos de acesso disponíveis, obtendo informações de seus SSIDs, endereços MAC, e força de sinal.  Isto pode ser usado em conjunto com geolocalização (Geolocation) para oferecer serviço de localização baseado em WiFi.
-
-

Mudanças e melhorias notáveis

- -

Novas características para usuários finais

-

Experiência do usuário

- -

Segurança e Privacidade

- -

Performance

- -

Veja também

- diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html deleted file mode 100644 index d385b99b81..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Atualizando extensões para o Firefox 3.5 -slug: Mozilla/Firefox/Releases/3.5/Updating_extensions -translation_of: Mozilla/Firefox/Releases/3.5/Updating_extensions -original_slug: Atualizando_extensões_para_o_Firefox_3.5 ---- -
{{FirefoxSidebar}}
-

Este artigo proporciona informação útil para desenvolvedores tentando atualizar suas extensões para trabalharem corretamente no Firefox 3.5.

-

Atualizações básicas

-

Esta seção cobre o básico do que você necessita fazer sempre que você atualiza uma extensão para uma nova versão do Firefox.

-

Teste sua extensão

-

Começe editando o arquivo install.rdf da sua extensão, atualizando maxVersion para 3.5b4 (if you're testing on Firefox 3.5 beta 4), e aumente a versão da sua extensão.
-
- Crie então um novo perfil no Firefox, para que os testes não coloquem em risco seu perfil usual. Navegue até o diretório contendo Firefox, e então digite o comando:

-
firefox -createProfile testBeta4
-
-

No Mac, você precisa navegar por todo o caminho da bundle aplicação Firefox:

-
cd /Applications/Firefox.app/Contents/MacOS/
-firefox -createProfile testBeta4
-
-

Inicie o Firefox usando o novo perfil digitando este comando na linha de comeando:

-
firefox -P testBeta4
-
-

Teste a sua extensão cuidadosamente. Nós sugerimos que você configure as seguintes preferências para verdadeiro (true) com a finalidade de ser alertado para qualquer advertência ou exceção do JavaScript:

- -

Atualize sua extensão

-

Se você encontrar algum problema durante o teste, atualize seu código para corrigir os problemas. Este artigo contém informação sobre coisas que podem requisitar algum trabalho.
-
- Uma vez que tenha feito isto, tente usar sua extensão novamente, desta vez com o perfil normal. Isto ajudará a assegurar a compatibilidade com qualquer dado existente salvo.

-

Atualize sua extensão em addons.mozilla.org

-

Finalmente, é hora de lançar sua extensão atualizada. Se a sua extensão não necessita de qualquer mudança no código, você pode simplesmente conectar-se ao painel AMO e atualizar a compatibilidade da versão por ali. Caso contrário será necessário enviar uma nova versão para o AMO.
-
- Veja Submitting an add-on to AMO (EN) para informações adicionais.

-

Acessando o banco de dados do Places

-

Antes do Firefox 3.5, acessar o banco de dados do Places diretamente usando a API de Armazenamento (Storage API (EN)) requeria alguns truques:

-
var places = Components.classes["@mozilla.org/file/directory_service;1"].
-                        getService(Components.interfaces.nsIProperties).
-                        get("ProfD", Components.interfaces.nsIFile);
-places.append("places.sqlite");
-var db = Components.classes["@mozilla.org/storage/service;1"].
-                    getService(Components.interfaces.mozIStorageService).openDatabase(places);
-
-

Isto constrói um caminho manual para o arquivo do banco de dados places.sqlite database, então abre o arquivo para o acesso ao armazenamento.

-

O Firefox 3.5 adiciona um serviço dedicado que oferece uma maneira mais conveniente para acessar o banco de dados do Places; a técnica a seguir não funciona no Firefox 3.5 ou anteriores.

-
var db = Components.classes["@mozilla.org/browser/nav-history-service;1"].
-                    getService(Components.interfaces.nsPIPlacesDatabase).DBConnection;
-
-

Caixas de texto de Pesquisa

-

O tipo de caixa de texto (textbox (EN)) timed está depreciado; ao invés disso, você deve usar search.

-

No Firefox 3, você pode ter usado:

-
<textbox type="timed" timeout="1000" oncommand="alert(this.value);"/>
-
-

No Firefox 3.5, você deve mudar para:

-
<textbox type="search" timeout="1000" oncommand="alert(this.value);"/>
-
-

JSON

-

O módulo JavaScript JSON.jsm foi removido no Firefox 3.5 em favor do suporte nativo ao objeto JSON. Para detalhes, veja Using JSON in Firefox (EN) e o artigo em JSON (EN) para uma introdução mais geral sobre o JSON e como usá-lo em várias versões do Firefox.

-

Para assegurar a compatibilidade com o Firefox 3 e Firefox 3.5, você pode fazer o que segue:

-
if (typeof(JSON) == "undefined") {
-  Components.utils.import("resource://gre/modules/JSON.jsm");
-  JSON.parse = JSON.fromString;
-  JSON.stringify = JSON.toString;
-}
-
-

Isto funciona importando o módulo JavaScript JSON.jsm se o JSON não for suportado nativamente, mapeando então os métodos proporcionados por este módulo aos usados nativamente no JSON, então as mesmas chamadas funcinam.

-

Você pode também contornar este problema usando a interface {{ interface("nsIJSON") }} diretamente.

-

Mudanças nos menus de contexto

-

Com o objetivo de suportar as novas características de áudio e vídeo adicionadas ao Gecko 1.9.1, a classe de nsContextMenu foi renomeada de imageURL para mediaURL; entretanto, imageURL foi adicionado novamente em 9 de junho de, 2009.

-

Mudanças no registro chrome

-

O Firefox 3.5 corrige falhas de segurança que tornam possível o uso remoto do chrome. Isto afetará qualquer complemento que inclua recursos em seu arquivo chrome.manifest que referencie a um web site, dados ou urls de recursos. Veja Security changes in Firefox 3.5 (EN) para detalhes.

-

Conseguindo um contexto carregado através de requisição

-

Anteriormente, era possível conseguir um contexto carregado a partir de uma requisição por consulta a várias APIs docShell. Uma maneira correta e confiável de fazer isso é usar um {{ interface("nsILoadContext") }}.

-

Com o C++, você pode fazer como mostrado abaixo:

-
nsCOMPtr<nsILoadContext> loadContext;
-nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
-NS_QueryNotificationCallbacks(channel, loadContext);
-
-

Com o JavaScript, você pode fazer desta maneira:

-
var loadContext;
-try {
-  loadContext =
-    aRequest.queryInterface(Components.interfaces.nsIChannel)
-            .notificationCallbacks
-            .getInterface(Components.interfaces.nsILoadContext);
-} catch (ex) {
-  try {
-    loadContext =
-      aRequest.loadGroup.notificationCallbacks
-              .getInterface(Components.interfaces.nsILoadContext);
-  } catch (ex) {
-    loadContext = null;
-  }
-}
-
-

Barra de ferramentas customizável

-

No Firefox 3.5, o comportamento da barra de ferramentas customizável mudou, tal que o vínculo <xul:toolbar/> agora remove itens da barra de ferramentas do seu associado <xul:toolbarpalette/> e os adiciona na barra de ferramentas, ao invés de cloná-los e copiá-os para a barra de ferramentas. Isto significa que a paleta conterá agora somente itens não presentes na barra de ferramentas, ao contrário do comportamento anterior de conter todos os elementos, customizáveis ou não, exibidos na barra de ferramentas. Isto pode causar problemas para complementos dependendo da possibilidade de recuperar os itens da barra de ferramentas customizável através de <xul:toolbarpalette/>, ou de tentar dinamicamente inserir itens na paleta para torná-la disponível durante a customização da barra de ferramentas. Mais informações está disponível em {{ Bug(407725) }} e {{ Bug(467045) }}.

-

XPCNativeWrapper

-

Iniciando o Firefox 3.5, você não pode mais usar data: you can no longer use data: bindings em pacotes chromeque possuem automatização XPCNativeWrapper. Isto resolve um potencial problema de segurança.

-

Documentos XUL agora tem o tratamento XPCNativeWrapper, então você agora precisa usar o método getAttribute() para buscar valores de atributo ao invés de simplesmente lê-los diretamente.

-

Se a sua extensão está usando xpcnativewrappers=no (o que não deveria ser feito em primeiro lugar, uma vez que não é seguro fazê-lo), o XBL desta extensão não será aplicado a documentos que estejam usando automatização XPCNativeWrapper, começando no Firefox 3.5.

-

Novas características interessantes

-

"Listening" eventos em todas as abas

-

O Firefox 3.5 adicionou suporte para a adição e remoção de listeners que listen em todas as abas. Veja Listening to events on all tabs (EN) para detalhes.

-

Para desenvolvedores de temas:

- -

 

diff --git a/files/pt-pt/mozilla/firefox/releases/3.6/index.html b/files/pt-pt/mozilla/firefox/releases/3.6/index.html deleted file mode 100644 index 1413f08199..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.6/index.html +++ /dev/null @@ -1,310 +0,0 @@ ---- -title: Firefox 3.6 para desenvolvedores -slug: Mozilla/Firefox/Releases/3.6 -translation_of: Mozilla/Firefox/Releases/3.6 -original_slug: Firefox_3.6_para_desenvolvedores ---- -

Firefox 3.6 oferece suporte para padrões web novos e em desenvolvimento, performance melhorada e uma boa experiência para usuários web e desenvolvedores. Está página proporciona links para artigos cobrindo as novas capacidades do Firefox 3.6.

- -

Para desenvolvedores de websites e aplicações

- -

CSS

- -
-
Using gradients
-
Firefox 3.6 adicionou o suporte às propriedades sugeridas -moz-linear-gradient e -moz-radial-gradient para background.
-
Multiple backgrounds
-
A propriedade background (assim como background-color, background-image, background-position, background-repeat e background-attachment) agora suporta múltiplos fundos de tela. Isto permite a especificação de múltiplos fundos de tela que são renderizados um sobre o outro, em camadas.
-
Mozilla-specific media features
-
Características de mídia foram adicionadas para o sistema de métricas específico da Mozilla, então consultas de mídia podem ser usadas para checar mais seguramente a disponibilidade de características como o suporte a toque.
-
Scaling background images
-
A propriedade background-size do CSS 3 Backgrounds and Borders draft é agora suportada sob o nome -moz-background-size.
-
WOFF font support
-
@font-face agora suporta arquivos de fonte baixáveis no formato WOFF.
-
Pointer events
-
A propriedade pointer-events permite ao conteúdo especificar quando um elemento pode ser o alvo ou não de eventos com o ponteiro do mouse.
-
- -

Miscelânea de mudanças no CSS

- - - -

HTML 

- -
-
Using files from web applications
-
Suporte para a nova API de Arquivos HTML5 foi adicionada ao Gecko, tornando possível para aplicações web acessar arquivos locais selecionados pelo usuário. Isto inclui suporte para a seleção de múltiplos arquivos usando o novo atributo multiple do elemento HTML input type="file".
-
HTML5 vídeo suporta quadros poster
-
O atributo poster é agora suportado pelo elemento video, permitindo ao conteúdo especificar um quadro poster a ser exibido até que o vídeo comece a tocar.
-
Checkboxes e radio buttons suportam a propriedade indeterminate
-
Os elementos HTML input dos tipos checkbox e radio agora suportam a propriedade indeterminate, que permite um terceiro estado "indeterminado".
-
A suavização de imagens em canvas pode ser controlada
-
A nova propriedade mozImageSmoothingEnabled pode ser usada para ativar e desativar a suavização de imagens quando mudando a escala em elementos canvas.
-
Execução de script assíncrona
-
Configurando o atributo async no elemento script, o script não bloqueará o carregamento ou exibição do resto da página. Ao invés, o script executa assim que for baixado.
-
- -

JavaScript

- -

O Gecko 1.9.2 introduz o JavaScript 1.8.2, o qual adiciona algumas características da linguagem do ECMAScript 5 standard:

- - - -

DOM

- -
-
- -

Miscelânea de mudanças no DOM

- - - -
-
Web workers podem agora se auto-terminar
-
Workers agora suportam o método nsIWorkerScope.close(), que permite a eles, terminá-los eles mesmos.
-
Arrastar e soltar (drag and drop) agora suportam arquivos
-
O objeto DataTransfer previsto para arrastar listeners agora inclui uma lista de arquivos que foram arrastados.
-
Checando para ver se um elemento combina com um seletor CSS especificado
-
O novo método element.mozMatchesSelector permite a determinação se um elemento combina ou não com um seletor CSS especificado. Veja bug 518003.
-
Detecting device orientation
-
 
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Detecting document width and height changes
-
O novo evento MozScrollAreaChanged  é despachado sempre que as propriedades scrollWidth e/ou scrollHeight do documento mudam.
-
 
-
- -

XPath

- -
-
O método choose() do XPath é agora suportado
-
O método choose() é agora suportado pela nossa implementação do XPath.
-
- -

Para desenvolvedores XUL e de complementos

- -

Se você é um desenvolvedor de extensões, deveria começar lendo Updating extensions for Firefox 3.6, o qual oferece uma introdução útil de que mudanças podem afetar sua extensão. Desenvolvedores de plug-ins deveriam ler Updating plug-ins for Firefox 3.6.

- -

Novas Características

- -
-
Detecting device orientation
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Monitoring HTTP activity
-
É possível agora monitorar transações HTTP para observar requisições e respostas em tempo real.
-
Working with the Windows taskbar
-
É possível agora customizar a aparência das janelas na barra de tarefas no Windows 7 ou mais recentes.
-
- -

Places

- - - -

Storage

- -
-
Locale-aware collation of data is now supported by the Storage API
-
O Gecko 1.9.2 adicionou várias novos métodos de agrupamento para proporcionar o agrupamento otimizado (classificação) de resultados usando técnicas de localização-consciente.
-
Properties on a statement can now be enumerated
-
Você pode agora usar a enumeração for..in para enumerar todas as propriedades de uma declaração.
-
mozIStorageStatement's getParameterIndex teve o comportamento alterado entre 3.5 e 3.6.
-
Veja bug 528166 para detalhes.
-
Ligar vários conjuntos de parâmetros assincronamente para executar uma declaração.
-
Veja bug 490085 para detalhes. A documentação virá em breve.
-
- -

Preferências

- - - -

Temas

- -

Veja Updating themes for Firefox 3.6 para detalhes.

- -
-
Lightweight themes
-
O Firefox 3.6 suporta temas leves; estes são temas fáceis de criar que simplesmente aplicam uma imagem de fundo ao topo (barra de endereços e barra de botões) e inferior (barra de estado (status)) das janelas do navegador. Esta é uma integração à arquitetura de temas existente Personas no Firefox.
-
- -

 

- -

Miscelânea

- - - -

Para desenvolvedores Firefox/Gecko

- -

Algumas mudanças são interessantes somente se você trabalha internamente no próprio Firefox.

- -

Interfaces mescladas

- -

As seguintes interfaces foram unidas:

- - - -

Interfaces removidas

- -

As seguintes interfaces foram removidas inteiramente porque eram obsoletas, não utilizadas ou não implementadas:

- - - -

Interfaces movidas

- -

As seguintes interfaces foram realocadas de seus arquivos IDL anteriores em novos:

- - - -

Um grande número de interfaces foram movidas. Veja Interfaces moved in Firefox 3.6 para uma lista completa.

- -

Outras mudanças na interface

- -

As seguintes alterações foram feitas:

- - - -

 

- -

Mudanças na acessibilidade do código

- - - -

Veja também

- - diff --git a/files/pt-pt/mozilla/firefox/releases/3/index.html b/files/pt-pt/mozilla/firefox/releases/3/index.html deleted file mode 100644 index 129fa2fc1e..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Firefox 3 for developers -slug: Mozilla/Firefox/Releases/3 -tags: - - Firefox 3 - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Firefox/Releases/3 ---- -
{{FirefoxSidebar}}

If you're a developer trying to get a handle on all the new features in Firefox 3, this is the perfect place to start. This article provides a list of the new articles covering features added to Firefox 3. While it doesn't necessarily cover every little change, it will help you learn about the major improvements.

-

New developer features in Firefox 3

-

For web site and application developers

-
-
- Updating web applications for Firefox 3
-
- Provides information about changes you may need to make to your web site or web application to take advantage of new features in Firefox 3.
-
-
-
- Online and offline events
-
- Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
-
-
-
- Web-based protocol handlers
-
- You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
-
-
-
- Drawing text using a canvas
-
- You can now draw text in a canvas using a non-standardized API supported by Firefox 3.
-
-
-
- Transform support for canvas
-
- Firefox now supports the transform() and setTransform() methods on canvases.
-
-
-
- Using microformats
-
- Firefox now has APIs for working with microformats.
-
-
-
- Drag and drop events
-
- Firefox 3 supports new events that are sent to the source node for a drag operation when the drag begins and ends.
-
-
-
- Focus management in HTML
-
- The new HTML 5 activeElement and hasFocus attributes are supported.
-
-
-
- Offline resources in Firefox
-
- Firefox now lets web applications request that resources be cached to allow the application to be used while offline.
-
-
-
- CSS improvements in Firefox 3
-
- Firefox 3 features a number of improvements in its CSS support.
-
-
-
- DOM improvements in Firefox 3
-
- Firefox 3 offers a number of new features in Firefox 3's DOM implementation, including support for several Internet Explorer extensions to the DOM.
-
-
-
- JavaScript 1.8 support
-
- Firefox 3 offers JavaScript 1.8.
-
-
-
- EXSLT support
-
- Firefox 3 provides support for a substantial subset of the EXSLT extensions to XSLT.
-
-
-
- SVG improvements in Firefox 3
-
- SVG support in Firefox 3 has been upgraded significantly, with support for over two dozen new filters, several new elements and attributes, and other improvements.
-
-
-
- Animated PNG graphics
-
- Firefox 3 supports the animated PNG (APNG) image format.
-
-

For XUL and extension developers

-

Notable changes and improvements

-
-
- Updating extensions for Firefox 3
-
- Provides a guide to the things you'll need to do to update your extension to work with Firefox 3.
-
-
-
- XUL improvements in Firefox 3
-
- Firefox 3 offers a number of new XUL elements, including new sliding scales, the date and time pickers, and spin buttons.
-
-
-
- Templates in Firefox 3
-
- Templates have been significantly improved in Firefox 3. The key improvement allows the use of custom query processors to allow data sources other than RDF to be used.
-
-
-
- Securing updates
-
- In order to provide a more secure add-on upgrade path for users, add-ons are now required to provide a secure method for obtaining updates before they can be installed. Add-ons hosted at AMO automatically provide this. Any add-ons installed that do not provide a secure update method when the user upgrades to Firefox 3 will be automatically disabled. Firefox will however continue to check for updates to the extension over the insecure path and attempt to install any update offered (installation will fail if the update also fails to provide a secure update method).
-
-
-
- Places migration guide
-
- An article about how to update an existing extension to use the Places API.
-
-
-
- Download Manager improvements in Firefox 3
-
- The Firefox 3 Download Manager features new and improved APIs, including support for multiple progress listeners.
-
-
-
- Using nsILoginManager
-
- The Password Manager has been replaced by the new Login Manager.
-
-
-
- Embedding XBL bindings
-
- You can now use the data: URL scheme from chrome code to embed XBL bindings directly instead of having them in separate XML files.
-
-
-
- Localizing extension descriptions
-
- Firefox 3 offers a new method for localizing add-on metadata. This lets the localized details be available as soon as the add-on has been downloaded, as well as when the add-on is disabled.
-
-
-
- Localization and Plurals
-
- Firefox 3 adds the new PluralForm module, which provides tools to aid in correctly pluralizing words in multiple localizations.
-
-
-
- Theme changes in Firefox 3
-
- Notes and information of use to people who want to create themes for Firefox 3.
-
-

New components and functionality

-
-
- FUEL Library
-
- FUEL is about making it easier for extension developers to be productive, by minimizing some of the XPCOM formality and adding some "modern" JavaScript ideas.
-
-
-
- Places
-
- The history and bookmarks APIs have been completely replaced by the new Places API.
-
-
-
- Idle service
-
- Firefox 3 offers the new {{Interface("nsIIdleService")}} interface, which lets extensions determine how long it's been since the user last pressed a key or moved their mouse.
-
-
-
- ZIP writer
-
- The new {{Interface("nsIZipWriter")}} interface lets extensions create ZIP archives.
-
-
-
- Full page zoom
-
- Firefox 3 improves the user experience by offering full page zoom in addition to text-only zoom.
-
-
-
- Interfacing with the XPCOM cycle collector
-
- XPCOM code can now take advantage of the cycle collector, which helps ensure that unused memory gets released instead of leaking.
-
-
-
- The Thread Manager
-
- Firefox 3 provides the new {{Interface("nsIThreadManager")}} interface, along with new interfaces for threads and thread events, which provides a convenient way to create and manage threads in your code.
-
-
-
- JavaScript modules
-
- Firefox 3 now offers a new shared code module mechanism that lets you easily create modules in JavaScript that can be loaded by extensions and applications for use, much like shared libraries.
-
-
-
- The nsIJSON interface
-
- Firefox 3 offers the new {{Interface("nsIJSON")}} interface, which offers high-performance encoding and decoding of JSON strings.
-
-
-
- The nsIParentalControlsService interface
-
- Firefox 3 now supports the Microsoft Windows Vista parental controls feature, and allows code to interact with it.
-
-
-
- Using content preferences
-
- Firefox 3 includes a new service for getting and setting arbitrary site-specific preferences that extensions as well as core code can use to keep track of their users' preferences for individual sites.
-
-
-
- Plug-in Monitoring
-
- A new component of the plugin system is now available to measure how long it takes plugins (e.g., Macromedia Flash) to execute their calls.
-
-

Fixed bugs

-
-
- Notable bugs fixed in Firefox 3
-
- This article provides information about bugs that have been fixed in Firefox 3.
-
-

New features for end users

-

User experience

- -

Security and privacy

- -

Performance

- -

See also

- -
{{Firefox_for_developers('2')}}
diff --git a/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html b/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html deleted file mode 100644 index 3c8b290205..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Mudanças no Gecko 1.9 que afetam websites -slug: Mozilla/Firefox/Releases/3/Site_compatibility -tags: - - Desenvolvimento_Web - - Gecko - - Todas_as_Categorias -translation_of: Mozilla/Firefox/Releases/3/Site_compatibility -original_slug: Mudanças_no_Gecko_1.9_que_afetam_websites ---- -
{{FirefoxSidebar}}
- -

Esta página tenta dar uma introdução das mudanças entre o Gecko 1.8 e o Gecko 1.9, que poderia possivelmente afetar websites em seu comportamento ou interpretação. Veja também Firefox 3 para desenvolvedores.

- -

Eventos

- -

Capturando ouvintes de carregamento de eventos

- -

No Gecko 1.8, não era possível configurar a captura de ouvintes de carregamento de eventos em imagens. No Gecko 1.9, isto foi corrigido por {{ Bug(234455) }}. Mas isto pode causar problemas em websites que tenham seus ouvintes de eventos incorretamente configurados para capturar o carregamento de evento. Veja a discussão em {{ Bug(335251) }}. Para corrigir este problema, a página problemática em questão não deve configurar uma captura de ouvintes de carregamento de eventos.

- -

Por exemplo, isto:

- -
window.addEventListener('load', yourFunction, true);
-
- -

deve ser mudado nisto:

- -
window.addEventListener('load', yourFunction, false);
-
- -

Para uma explanação de como eventos de captura trabalham, veja DOM Level 2 Event capture

- -

preventBubble foi removido

- -

No Gecko 1.8, o método preventBubble existia em eventos para previnir eventos de "borbulhar para cima". No Gecko 1.9 este método foi removido. Dessa forma, você deve usar o padrão stopPropagation(), o qual também trabalha bem no Gecko 1.8. Opatch em {{ Bug(330494) }} fez isto acontecer. Veja também {{ Bug(105280) }}.

- -

Algumas outras APIs de evento antigas não são mais suportadas

- -

window.captureEvents, window.releaseEvents, e window.routeEvent são são mais suportadas ({{ Obsolete_inline() }}) no Gecko 1.9.

- -

DOM

- -

WRONG_DOCUMENT_ERR

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Alcances

- -

intersectsNode foi removido

- -

No Gecko 1.8 a função do código intersectsNode é usada para testar se um nó intercepta um alcance. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Dessa forma use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para intersectsNode para como usar compareBoundaryPoints em vez disso.

- -

compareNode foi removido

- -

No Gecko 1.8 a função do código compareNode é usada para testar como um nó intercepta um alcante. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Em vez disso use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para compareNode para como usar compareBoundaryPoints em vez disso.

- -

HTML

- -

Muitosbugs em <object> foram corrigidos

- -

Os elementos object e embed não precisam mais do atributo type para interpretar. Mudando o atributo src (de <embed>) ou o atributo data (de <object>) via JavaScript agora trabalha corretamente. O cabeçalho Conteúdo-Tipo enviado pelo servidor (se algum) agora toma procedências sobre o atributo type de um elemento <object> de acordo com a especificação HTML. (este não é o caso de embed).

- -


- Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/Gecko_1.9_Changes_affecting_websites", "fr": "fr/Changements_dans_Gecko_1.9_affectant_les_sites_Web", "ja": "ja/Gecko_1.9_Changes_affecting_websites", "ko": "ko/Gecko_1.9_Changes_affecting_websites", "pl": "pl/Zmiany_w_Gecko_1.9_wp\u0142ywaj\u0105ce_na_wy\u015bwietlanie_stron" } ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html deleted file mode 100644 index d213047978..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Atualização das extensões para o Firefox 3 -slug: Mozilla/Firefox/Releases/3/Updating_extensions -tags: - - Firefox 3 -translation_of: Mozilla/Firefox/Releases/3/Updating_extensions -original_slug: Atualizando_extensões_para_o_Firefox_3 ---- -
- -

Este artigo proporciona informações úteis para desenvolvedores que desejam atualizar suas extensões para que funcionem corretamente no Firefox 3.

- -

Antes de continuar, há uma sugestão útil que podemos oferecer: se a única mudança que sua extensão requere é uma atualização no campo maxVersion no seu manifesto de instalação, e você hospedou sua extensão em addons.mozilla.org, você atualmente não precisa disponibilizar uma nova versão da sua extensão! Simplesmente use o Painel de Controle de Desenvolvedores em AMO para ajustar o maxVersion. Você pode evitar de ter sua extensão re-revisada por este caminho.

- -

Passo 1: Atualizar o manifesto de instalação

- -

O primeiro passo -- e, para muitas das extensões, o único que será necessário -- é atualizar o arquivo manifesto de instalação, install.rdf, para indicar compatibilidade com o Firefox 3.

- -

Simplesmente ache a linha que indica a máxima versão compatível do Firefox (que, para o Firefox 2, pode indicar como aqui):

- -
 <em:maxVersion>2.0.0.*</em:maxVersion>
-
- -

Mude isto para indicar compatibilidade com o Firefox 3:

- -
 <em:maxVersion>3.0.*</em:maxVersion>
-
- -

Então reinstale sua extensão.

- -

Note que o Firefox 3 acaba com o ".0" extra no número da versão, então, ao invés de usar "3.0.0.*", você precisa usar somente "3.0.*".

- -
Nota: Note que neste ponto mais mudanças no Firefox 3 são esperadas. Estas mudanças podem quebrar algumas extensões, então você não precisa lançar sua extensão com 3.0.* maxVersion para os usuários antes que o Firefox 3 candidato a liberação seja lançado. Durante o período do Firefox 3 Beta, você pode usar 3.0b5 como sua maxVersion.
- -

Tem havido (e continuará a haver) um número de mudanças na API que poderão quebrar algumas extensões. Nós estamos trabalhando na compilação de uma lista completa destas mudanças.

- -
Nota: Se a sua extensão ainda usa um script Install.js ao invés de um manifesto de instalação, você precisa fazer a transição para um manifesto de instalação agora. O Firefox 3 não mais suporta os scripts install.js em arquivos XPI.
- -

Adicionando localizações para o manifesto de instalação

- -

O Firefox 3 suporta novas propriedades no manifesto de instalação para especificar descrições localizadas. Os antigos métodos ainda funcionam, entretanto o novo Firefox permite pegar as localizações sempre que os complementos estiverem desabilitados e com instalação pendente. Veja Localizar descrições de extensões para mais detalhes.

- -

Passo 2: Certificar-se de que está a proporcionar atualizações seguras

- -

Se você está hospedando complementos por si mesmo e não em um provedor de hospedagem de complementos seguro como addons.mozilla.org então você precisa oferecer um método seguro de atualizar seu complemento. Isto poderá envolver a hospedagem das suas atualizações em um website SSL, ou usando chaves criptográficas para assinar a informação da atualização. Leia Securing Updates para mais informações.

- -

Passo 3: Lidar com APIs alteradas

- -

Várias APIs foram alterados de maneira significativa. O mais significativo destes, que provavelmente afetará um grande número de extensões, são:

- -

DOM

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Marcadores & Histórico

- -

Se sua extensão acessa dados dos favoritos ou do histórico de alguma maneira, ela precisará de um trabalho substancial para tornar-se compatível com o Firefox 3. As antigas APIs de acesso a estas informações foram substituidas pela nova arquitetura en:Places. Veja Migration Guide for Places para detalhes na atualização da sua extensão existente para usar a API Places.

- -

Gestor de Descargas

- -

A API do Gestor de Descargas foi alterado ligeiramente devido à transição de um RDF para armazenar dados usando a API en:Storage. Esta pode ser uma transição muito fácil de fazer. Além disso, a API de monitoramento do progesso de downloads mudou para suportar múltiplos receptores no gestor de descargas. Consulte en:nsIDownloadManager, en:nsIDownloadProgressListener, e en:Monitoring downloads para mais informação.

- -

Gestor de Palavras-passe

- -

Se sua extensão acessa informações do login de usuário usando o Gerenciador de Senhas, será necessário atualizá-la para usar a nova API de Gerenciamento de Login.

- - - -

Você pode também sobrepor o armazenamento do gerenciador de senhas construído se você desejar fornecer a implementação de seu próprio armazenamento de senhas nas suas extensões. Veja Criando um módulo de armazenamento de Gerenciador de Login para mais detalhes.

- -

janelas (Menus, Menus de Contexto, Dicas de Ferramenta e Painéis)

- -

O sistema de Popup XUL foi bastante modificado no Firefox 3. O sistema de Popup inclui menus principais, menus de contexto e painéis popup. Um guia sobre como usar Popups foi criado, detalhando como o sistema trabalha. Uma coisa a se notar é que popup.showPopup foi depreciado em favor do novo popup.openPopup e popup.openPopupAtScreen.

- -

Auto Completar

- -

O método handleEnter() da interface en:nsIAutoCompleteController foi alterado para aceitar um argumento que indica quando o texto foi selecionado do popup autocompletar ou pelo usuário pressionando enter depois de digitar o texto.

- -

DOMParser

- - - -

Interfaces removidas

- -

As seguintes interfaces foram removidas do Gecko 1.9, que direcionam o Firefox 3. Se sua extensão faz uso de alguma destas, você precisará atualizar seu código:

- - - -

Passo 4: Procurar por alterações relevantes no chrome

- -

Houveram menores mudanças no chrome que podem requisitar mudanças no seu código. Uma nova vbox foi adicionada, chamada "browser-bottombox", que inclui a barra de procura e a barra de estado à janela do navegador. Embora ela não afete a aparência da exibição, ela pode afetar sua extensão se ela sobrepuser o chrome em relação a estes elementos.

- -

Por exemplo, se você anteriormente sobrepôs algum chrome antes da barra de estado, como isto:

- -
<window id="main-window">
-  <something insertbefore="status-bar" />
-</window>
-
- -

Você deve agora sobrepor desta maneira:

- -
<vbox id="browser-bottombox">
-  <something insertbefore="status-bar" />
-</vbox>
-
- -

Outras alterações

- -

Mudanças simples adicionais que tiver de fazer enquanto atualiza sua extensão para trabalhar com o Firefox 3, aqui.

- - - -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/mozilla/firefox/releases/4/index.html b/files/pt-pt/mozilla/firefox/releases/4/index.html deleted file mode 100644 index a79356442c..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/4/index.html +++ /dev/null @@ -1,657 +0,0 @@ ---- -title: Firefox 4 para desenvolvedores -slug: Mozilla/Firefox/Releases/4 -tags: - - CSS - - Firefox - - Firefox 4 - - Gecko - - Gecko 2.0 - - HTML - - JavaScript - - XPCOM - - XUL -translation_of: Mozilla/Firefox/Releases/4 -original_slug: Firefox_4_para_desenvolvedores ---- -
- -
-

Esboço
- Esta página está incompleta.

- -
- -

O Firefox 4, o qual entrou em beta no mês de junho de 2010, melhora a performance, adiciona maior suporte ao HTML5 e outras tecnologias web envolvidas e, além disso, melhora a segurança. Este artigo proporciona informações iniciais sobre o lançamento que virá e quais funcionalidades estão disponíveis, tanto para desenvolvedores web, quanto para desenvolvedores de complementos e desenvolvedores da plataforma Gecko.

- -

Muitas destas funcionalidades já podem ser testadas na versão Firefox 4 beta, ou, se estiver se sentindo aventureiro, em nightly trunk builds.

- -
Observação: Este artigo é um trabalho em progresso, assim como todos os artigos linkados nesta página. Muitos nomes de artigos são espaços reservadis e alguns tópicos provavelmente serão quebrados em múltiplos artigos. Em geral, seja cuidadoso ao vincular páginas a estes artigos, por enquantoIn general, be cautious about linking to these articles for the time beingJavas.
- -

Funcionalidades para desenvolvedores web

- -

O Gecko agora usa o analisador HTML5 (parser HTML5), que corrige bugs, melhora a interoperabilidade e melhora a performance. Ele também permite conteúdos de SVG e MathML embutidos diretamente na marcação HTML.

- -

HTML

- -
-
Conheça o parser HTML5
-
Uma olhada no que o analisador HTML5 (parser HTML5) significa para você e como incorporar SVG e MathML ao seu conteúdo.
-
Forms no HTML5
-
Uma olhada às melhorias aos web forms no HTML5. Entre estas mudanças foram adicionados tipos de entrada no elemento <input> e validação de dados, dentre outros.
-
Seções HTML5
-
O Gecko agora suporta os novos elementos HTML5 relacionados a seções em um um documento: <article>, <section>, <nav>, <aside>, <hgroup>, <header> e <footer>.
-
Outros elementos HTML5
-
O Gecko agora suporta os seguintes elementos do HTML5: <mark>, <figure><figcaption>.
-
WebSockets
-
Um guia para usar a nova API de WebSockets para comunicação em tempo real entre uma aplicação web e um servidor.
-
- -

Modificações HTML diversas

- - - -

CSS

- -
-
Transições CSS (CSS transitions)
-
O suporte à novas transições CSS está disponível no Firefox 4.
-
Valores calculados em CSS
-
Foi adicionado o suporte para -moz-calc. Isto permite especificar valores <length> como expressões matemáticas.
-
Seletor de agrupamento
-
Suporte a :-moz-any para agrupar seletores e fatorizar combinadores.
-
Suporte a sub-retângulo em imagens de fundo
-
A função -moz-image-rect torna possível o uso de subretângulos de imagens como uma background-image (imagem de plano de fundo).
-
Propriedades de toque CSS
-
O suporte para propriedades de toque foi adicionado. Detalhes e nomes de artigos reais, virão depois.
-
Using arbitrary elements as CSS backgrounds
-
Você pode usar a função -moz-element do CSS e a função document.mozSetImageElement() do DOM para usar elementos HTML arbitrários como planos de fundos.
-
Privacidade e o seletor :visited
-
Mudanças foram feitas ao tipo de informação que pode ser obtida sobre o estilo dos links visitados usando seletores CSS. Isto pode afetas algumas aplicações web.
-
- -

Novas propriedades do CSS

- - - - - - - - - - - - - - - - - - - - -
PropriedadeDescrição
-moz-font-feature-settingsPermite características avançadas de customização em fontes OpenType.
-moz-tab-sizeEspecifica a largura em caracteres de espaço, de um caracter tab (U+0009) na renderização de texto.
resizePermite o controle das dimensões nas quais um elemento pode ser redimensionado.
- -

Novas pseudo-classes do CSS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pseudo-classeDescrição
:-moz-handler-crashedUsado para estilizar elementos cujos plugins tenham quebrado.
:-moz-placeholderAplicado ao espaço reservado de texto nos campos de formulário.
:-moz-submit-invalidAplicado ao botão de submeter em formulários quando um ou mais dos campos do formulário não é validado.
:-moz-window-inactiveAplicado a elementos em janelas inativas.
:invalidAplicado automaticamente para os campos <input> quando suas constantes são inválidas.
:optionalAplicado automaticamente para os campos <input> que não especifiquem o atributo required.
:requiredAplicado automaticamente para os campos <input> que especifiquem o atributo required.
:validAplicado automaticamente para os campos <input> quando suas constantes são validadas com sucesso.
- -

Novos pseudo-seletores do CSS

- - - - - - - - - - - - -
Pseudo-seletorDescrição
:-moz-focusringPermite especificar a aparência de um elemento quando o Gecko acredita que ele deve ter uma indicação de foco renderizada.
- -

Novas funções do CSS

- - - - - - - - - - - - - - - - - - - - - - - - -
FunçãoDescrição
:-moz-anyPermite agrupar seletores e fatorizar combinações.
-moz-calcPermite a especificação de valores <length> como expressões matemáticas.
-moz-elementPermite o uso de um elemento arbitrário como imagem de fundo para background-image e background.
-moz-image-rectPermite o uso de um sub-retângulo de uma imagem como um background-image ou background.
- -

Propriedades do CSS renomeadas

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Old NameNew NameNotes
-moz-background-sizebackground-sizeO nome -moz-background-size não é mais suportado.
-moz-border-radiusborder-radiusO antigo nome é suportado por tempo limitado para permitir a atualização de seus sites. Mudanças de renderização também foram feitas para conseguir a compatibilidade com a última versão.
-moz-box-shadowbox-shadow
- -

Modificações CSS diversas

- - - -

Modificações CSS diversas

- - - -

Gráficos e vídeo

- -
-
-
WebGL
-
O padrão de desenvolvimento WebGL é agora suportado pelo Firefox.
-
Otimização da performance gráfica
-
Dicas e truques para conseguir a melhor performance gráfica e de vídeo no Firefox 4.
-
Suporte a vídeos WebM
-
O novo formato aberto de vídeo WebM é suportado pelo Gecko 2.0; o suporte está incluído em nightlies desde 9 de junho.
-
Animação SVG com SMIL
-
O suporte a animações SMIL do SVG está agora disponível.
-
Usando SVG como imagens e como fundos de tela CSS
-
Você pode agora usar o SVG com o elemento <img>, assim como com a propriedade background-image do CSS.
-
Suporte ao atributo de mídia buffered
-
O atributo buffered nos elementos <video> e <audio> é agora suportado, permitindo a determinação de quais faixas de um arquivo de mídia foram carregadas. A interface TimeRanges do DOM foi implementada para suportar isto.
-
Atributo de mídia preload
-
O atributo preload da especificação do HTML5 foi implementado, substituindo o atributo anteriormente implementado (e não mais suportado) autobuffer. Isto afeta os elementos <video> e <audio>, assim como a interface nsIDOMHTMLMediaElement.
-
Melhoramentos no posicionamento de texto SVG
-
Agora é possível especificar listas para os valores das propriedades x, y, dx e dy nos elementos <text> e <tspan> do SVG. Isto permite controlar o posicionamento de cada caractere individualmente em uma string.
-
- -

DOM

- -
-
Arrays com tipos JavaScript
-
Foi adicionado suporte para os arrays com tipos JavaScript; eles permitem a manipulação de buffers contendo dados em raw usando tipos de dados nativos. Muitas API fazem uso disto, incluindo File API, WebGL, e WebSockets.
-
Obtenção de limites de retângulos para ranges
-
O objeto Range agora possui os métodos range.getClientRects() e range.getBoundingClientRect().
-
Captura de eventos de mouse em elementos arbitrários
-
O suporte para as APIs setCapture() e releaseCapture() originadas do Internet Explorer foram adicionadas. Veja bug 503943.
-
Manipulação do histórico do navegador
-
O objeto de histórico de documento existente, disponível através do objeto window.history agora suporta os novos métodos pushState() e replaceState() do HTML5.
-
Animações usando o MozBeforePaint
-
Um novo evento foi adicionado, o qual combinado com o método window.mozRequestAnimationFrame() e a propriedade window.mozAnimationStartTime, proporciona uma maneira de criar animações sincronizadas uma com a outra.
-
Eventos de toque e multi-toque
-
Foi adicionado suporte ao evetos de toque e multi-toque.
-
-
- -

A interface DOM dos elementos HTML mudou

- -

Muitos elementos do HTML tiveram suas interfaces DOM mudadas para aquelas requisitadas pela especificação do HTML5, como mostrado abaixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Interface no Firefox 3.6Interface no Firefox 4Elemento HTML
HTMLSpanElementHTMLElement<abbr>, <acronym>, <address>, <b>, <bdo>, <big>, <blink>, <center>, <cite>, <code>, <dd>, <dfn>, <dt>, <em>, <i>, <kbd>, <listing>, <nobr>, <plaintext>, <s>, <samp>, <small>, <strike>, <strong>, <sub>, <sup>, , <tt>, <u>, <var>, <xmp>
HTMLDivElementHTMLElement<noembed>, <noframes>, <noscript>
HTMLWBRElementHTMLElement<wbr>
- -

Modificações DOM diversas

- - - -

Segurança

- -
-
- -
-
Política de Segurança de Conteúdo (CSP)
-
A Política de Segurança de Conteúdo (Content Security Policy - CSP) é uma proposta da Mozilla desenvolvida para ajudar web designers e administradores de servidores a especificar como o conteúdo em seus sites interage. A meta é ajudar a detectar e abrandar ataques, incluindo cross-site scripting e ataques de injeção de dados.
-
Segurança de Transporte do HTTP Estrito (HTTP Strict Transport Security)
-
A Segurança de Transporte de HTTP Estrito é uma característica que permite a um website dizer ao navegador que ele deve ser comunicado somente usando HTTPS, ao invés de HTTP.
-
O cabeçalho de resposta (The X-FRAME-OPTIONS response header)
-
O cabeçalho de resposta HTTP, X-FRAME-OPTIONS, introduzido no Internet Explorer 8 é agora suportado pelo Firefox. Isto permite a sites indicar quando suas páginas devem ou não ser usadas em quadros (frames), e, em caso afirmativo, se deve ou não restringir isto à mesma origem.
-
Mudanças na string de Agente de Usuário (User Agent string) changes
-
Como um meio para reduzir a quantidade de dados e entropia descartada em requisições HTTP (veja bug 572650) a força da criptografia e tokens de linguagem foram removidos pela string do agente de usuário.
-
- -

JavaScript

- -

Para uma visão geral das mudanças implementadas em JavaScript 1.8.5, veja Novidades no JavaScript 1.8.5. O JavaScript no Firefox 4 terá aderência adicional ao padrão ECMAScript 5.

- -

Ferramentas para desenvolvedores

- -
-
Usando o Web Console
-
A ferramenta Web Console é um depurador útil para ajudar desenvolvedores web, assim como, desenvolvedores de extensões.
-
- -
-
-Gecko 2.0 note -
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
-
- -

O Console de Erros está inicialmente desabilitado por padrão no Firefox 4. Você pode reabilitá-lo mudando a preferência devtools.errorconsole.enabled para true e reiniciando seu navegador.

-
- -

Mudanças para desenvolvedores Mozilla e de complementos

- -

Para dicas úteis sobre a atualização de extensões existentes para o Firefox 4, veja Atualizando extensões para o Firefox 4. Existem muitas mudanças de chaves que quebram a compatibilidade com complementos existentes, então certifique-se de ler este artigo.

- -

Se você é um desenvolvedor de temas, você deve ler Mudanças nos temas do Firefox 4 (en) para entender algumas mudanças críticas, às quais é necessário estar ciente.

- -

Módulos de codificação JavaScript

- -
-
Services.jsm
-
O módulo de código Services.jsm fornece "getters" que tornam mais fácil a obtenção de referências a serviços comumente usados, como o serviço de preferências ou o mediador de janelas, entre outros.
-
- -
-
JS-ctypes API
-
A API JS-ctypes torna possível chamar funções de fora da biblioteca compatível com C, sem precisar usar o XPCOM.
-
Gerenciador de Complementos
-
O Gerenciador de Complementos fornece informações sobre complementos instalados, suporte à gerência dos mesmos e fornece maneiras para instalar e remover complementos.
-
PopupNotifications.jsm
-
O novo módulo de notificações popup torna fácil apresentar notificações atrativas, não modais para o usuário. Você pode ver como usar esta API em Usando notificações de popup (en).
-
Carregando módulos de código a partir de URL chrome: (en)
-
Você pode agora carregar módulos JavaScript usando URL chrome:, mesmo dentro de arquivos JAR.
-
DownloadLastDir.jsm
-
O módulo de código DownloadLastDir.jsm fornece a variável global, a qual contém uma string que pode ser usada para aprender o caminho do diretório no qual ocorreu o último download. Este módulo lida com questões relacionadas a privacidade de navegação do usuário.
-
Medindo a performance usando o módulo de código PerfMeasurement.jsm (en)
-
O módulo de código PerfMeasurement.jsm proporciona uma API para mensurar a performance dos dados a nível de CPU no código JavaScript.
-
- -

Mudanças diversas aos módulos de código

- - - -

Mudanças no DOM

- -
-
- -
-
ChromeWorker
-
Um novo tipo de worker para código privilegiado; ele permite o uso de coisas como js-ctypes de workers em extensões e código de aplicações.
-
Eventos de toque
-
Suporte para eventos de toque (não padrões) foi adicionado; isto permite detectar o movimento de múltiplos dedos movendo-se em uma tela ao mesmo tempo.
-
- -

XUL

- -

Mudanças no elemento tabbrowser

- -

Várias mudanças foram feitas ao elemento <xul:tabbrowser> que causam impactos nas extensões que interagem com as abas. Adicionalmente para suportar abas aplicativos, estas mudanças também mudam a barra de abas para uma barra de ferramentas padrão, a qual permite que o usário arraste botões da barra de ferramentas para ela.

- - - -

Mudanças para popups

- - - -

Suporte remoto ao XUL removido

- -

XUL remoto não é mais suportado; isto afeta os documentos XUL servidos através de HTTP; além disso, não é mais possível carregar documentos XUL usando URLs file:// a menos que você configure a preferência dom.allowXULXBL_for_file para true. Há, entretanto, um recurso de whitelist que pode ser usado para permitir domínios específicos a carregarem o XUL remotamente. O Remote XUL Manager extension permite o gerenciamento desta whitelist.

- -

Mudanças diversas no XUL

- - - -

Mudanças na IU que afetam os desenvolvedores

- -
-
A barra de complementos
-
O estado da barra foi removido em favor de uma nova barra de complementos. Será necessário atualizar sua extensão para usar isto se você já adicionou a IU à barra de estado no passado.
-
- -

Armazenamento

- -

Mudanças diversas na API storage (de armazenamento)

- - - -

XPCOM

- -

Em adição à mudanças específicas referenciadas abaixo, é importante notar que não existem mais interfaces estáticas. Todas as interfaces são dinâmicas, independente do que a documentação pode dizer. Atualizaremos a documentação com o tempo.

- -
-
Mudanças no XPCOM no Gecko 2.0
-
Detalhes sobre as mudanças para o XPCOM que causam algum impacto na compatibilidade do Firefox 4.
-
Components.utils.getGlobalForObject()
-
Este novo método retorna o objeto global com o qual um objeto é associado; ele substitui um caso de uso comum do agora removido __parent__.
-
- -

Places

- - - -

Mudanças na interface

- - - -

Gerenciamento de memória

- -
-
Alocação de memória infalível
-
A Mozilla, agora proporciona alocadores de memória infalíveis que são garantem que não haverá um retorno null. Você deve ler este artigo para aprender como eles trabalham e como solicitar explicitamente a alocação de memória falível versus invalível.
-
- -

Outras mudanças

- - - -

Outras mudanças

- -
-
Somente o arquivo chrome.manifest raiz é carregado
-
Agora somente o arquivo chrome.manifest raiz é carregado; se você necessitar de um arquivo de manifesto secundário para ser carregado, você pode usar o comando manifest no seu  chrome.manifest raiz para carregá-lo.
-
Removido o suporte ao Gopher
-
O protocolo Gopher não é mais suportado nativamente. O suporte continuado está disponível pela extensão OverbiteFF.
-
Processamento de eventos de manipulação de conteúdo
-
Com o objetivo de suportar plugins fora do processo e outra características de multi processamento, uma nova API foi introduzida para suportar o envio de mensagens através de processos.
-
- -
-
Extensões Bootstrapped (en)
-
Agora é possível criar extensões que podem ser instaladas, desinstaladas e atualizadas (ou desatualizadas) sem a necessidade de reiniciar o navegador.
-
- -
-
Plugin padrão removido
-
O plugin padrão foi removido. A pasta de aplicações plugin também foi removida por padrão, entretanto o suporte para a instalação de plugins através desta pasta ainda existe. Veja bug 533891.
-
Gerenciador de Extensões substituido pelo Gerenciador de Complementos
-
O nsIExtensionManager  foi substituido pelo Gerenciador de Complementos (en).
-
Os filhos HWND não são mais usados
-
O Firefox não cria mais filhos HWND para seu uso interno no Windows. Se você escreveu uma extensão que usa código nativo para manipular estas HWND, a sua extensão não funcionará no Firefox 4. Você precisará ou parar de usar HWND ou empacotar seu código dependente de HWND em um plugin NPAPI. Isto dará um grande trabalho, então se for possível não fazer uso do HWND diretamente, é recomendado evitá-lo.
-
Mudanças nos gestos
-
A rolagem com três dedos para cima ou para baixo em trackpads foi alterada para, por padrão, abrir e fechar a visão do Firefox Panorama (criado como TabCandy). Para voltar aos comando anteriores de rolagem para cima e para baixo, abra about:config e configure browser.gesture.swipe.down para cmd_scrollBottom e browser.gesture.swipe.up para cmd_scrollTop.
-
- -

Veja também

- - diff --git a/files/pt-pt/mozilla/firefox/releases/5/index.html b/files/pt-pt/mozilla/firefox/releases/5/index.html deleted file mode 100644 index 4565a3131d..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/5/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Firefox 5 para desenvolvedores -slug: Mozilla/Firefox/Releases/5 -translation_of: Mozilla/Firefox/Releases/5 -original_slug: Firefox_5_para_desenvolvedores ---- -
{{FirefoxSidebar}}

{{ draft() }}

-

O Firefox 5, é baseado no Gecko 5.0 e será lançado na metade de 2011. Este artigo proporciona links para informações sobre as mudanças que afetam os desenvolvedores nesta versão. Os nightly builds do futuro Firefox 5 estão disponíveis atualmente no canal Beta (iesto é, na seção mozilla-beta).

-
- Nota: Devido à maneira de funcionamento do processo de desenvolvimento, é possível que características atualmente listadas aqui possam ser transferidas para versões futuras do Firefox, por este motivo, por favor, fique atento a esta página.
-

Mudanças para desenvolvedores

-

HTML

- -

Melhorias no Canvas

- -

CSS

-
-
- CSS animations
-
- Foi adicionado o suporte para animações CSS, por enquanto com o uso do prefixo -moz-.
-
-

DOM

- -

JavaScript

- -

SVG

- -

HTTP

- -

MathML

- -

Ferramentas para desenvolvedores

- -

Mudanças para desenvolvedores de complementos e da Mozilla

-
- Nota: O Firefox 5 requere que componentes bionários sejam recompilados, assim como todas as versões maiores do Firefox. Veja Interfaces Binárias para detalhes.
-

Mudanças nos módulos de código do JavaScript

-

Novos módulos de códigos JavaScript

- -

NetUtil.jsm

- -

Mudanças na interface

- -

Ferramentas de depuração

- -

API JavaScript (SpiderMonkey)

- -

Mudanças no sistema de construção

- -

Veja também

- -

{{ languages( { "en": "en/Firefox_5_for developers"} ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/6/index.html b/files/pt-pt/mozilla/firefox/releases/6/index.html deleted file mode 100644 index 7f28326dce..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/6/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Firefox 6 para programadores -slug: Mozilla/Firefox/Releases/6 -translation_of: Mozilla/Firefox/Releases/6 -original_slug: Firefox_6_para_desenvolvedores ---- -
- -

O Firefox 6, baseado no Gecko 6.0, será lançado no dia 16 de agosto de 2011. Este artigo fornece hiperligações para a informação acerca das alterações que afetam os programadores neste lançamento.

- -

Alterações para os programadores da Web

- -

HTML

- -
-
- - - -

CSS

- -
-
-moz-text-decoration-color
-
Esta nova propriedade permite configurar a cor usada em decorações de texto, tais como sublinhados, sobrelinhados e rasurados.
-
-moz-text-decoration-line
-
Esta nova propriedade permite configurar o tipo de decoração de texto adicionado a um elemento.
-
-moz-text-decoration-style
-
Esta nova propriedade permite configurar o estilo das decorações de texto, tais como sublinhado, sobrelinhado e rasurado. Os estilos incluem simples tracejado, tracejado duplo, linha ondulada, linha pontilhada e assim por diante.
-
-moz-hyphens
-
Esta nova propriedade permite controlar como é tratada a hifenização das palavras quando ocorre uma quebra de linha.
-
-moz-orient
-
Uma nova propriedade (atualmente específica da Mozilla) a qual permite controlar a orientação: vertical ou horizontal, de certos elementos (particularmente <progress>).
-
::-moz-progress-bar
-
A Mozilla-specific pseudo-element that lets you style the area of an <progress> element representing the completed portion of a task.
-
- -

Outras alterações

- - - -

DOM

- -
-
Utilizar pedidos de multimédia do código (en)
-
Agora é possível testar o resultado de uma sequência de consulta de mídia programaticamente usando o método window.matchMedia() e a interface MediaQueryList.
-
- - - -

JavaScript

- - - -

SVG

- - - -

HTTP

- - - -

Cookies

- - - -

Outras alterações

- - - -

Alterações para os programadores de extras e da Mozilla

- -
Nota: o Firefox 6 necessita que os componentes binários sejam recompilados, assim como todos os lançamentos maiores do Firefox. Veja Interfaces Binárias (en) para detalhes.
- -

Módulos de código JavaScript

- -

FileUtils.jsm

- - - -

XPCOMUtils.jsm

- - - -

XPCOM

- - - -

Usando o DOM do chrome

- -
-
Using the DOM File API in chrome code
-
Embora sempre tenha sido possível utilizar a API File do DOM do código chrome, o construtor File agora suporta a especificação de uma string de nome de caminho local quando usada através do chrome. Adicionalmente, você também pode especificar o arquivo para acessar usando a API File do DOM usando um objeto nsIFile.
-
- -

Alterações da interface

- - - -

Novas interfaces

- - - -

Interfaces removidas

- - - -

Veja também

- - - -

Outras alterações

- -
-
Using preferences from application code
-
A new static API is available for easily accessing preferences; this is only available to application code and can't be used by add-ons.
-
- -

Consultar também

- -
diff --git a/files/pt-pt/mozilla/firefox/releases/70/index.html b/files/pt-pt/mozilla/firefox/releases/70/index.html deleted file mode 100644 index 7b67fba949..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/70/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Firefox 70 para programadores -slug: Mozilla/Firefox/Releases/70 -tags: - - '70' - - Firefox - - Lançamento - - Mozilla -translation_of: Mozilla/Firefox/Releases/70 ---- -

{{FirefoxSidebar}}{{Draft}}

- -

Este artigo fornece informaçaõ acerca das alterações no Firefox 70 que irão afetar od programadores. O Firefox 70 é a versão Beta atual do Firefox, e irá ser distribuida no dia 22 de outubro de 2019.

- -

Alterações para os programadores da Web

- -

Ferramentas do programador

- - - -

Removals

- -

HTML

- -

No changes.

- -

 Removals

- -

CSS

- - - -

Removals

- - - -

SVG

- -

No changes.

- -

Removals

- -

JavaScript

- - - -

Removals

- -

APIs

- - - -

Novas APIs

- -

DOM

- - - -

Eventos DOM

- -

Service workers

- -

Media, Web Audio, and WebRTC

- -

Canvas and WebGL

- - - -

Removals

- -

Segurança

- -

No changes.

- -

Removals

- -

Plug-ins

- -

No changes.

- -

Removals

- -

Outros

- -

No changes.

- -

Removals

- -

Alterações para os programadores de extras (add-on)

- -

Alterações de API

- -

Sem alterações.

- -

Removals

- -

Alfetarções de Manifest

- -

Sem alterações.

- -

Removals

- -

Consultar também:

- - - -

Versões antigas

- -

{{Firefox_for_developers(69)}}

diff --git a/files/pt-pt/mozilla/firefox/releases/index.html b/files/pt-pt/mozilla/firefox/releases/index.html deleted file mode 100644 index 68bc5d41e9..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Firefox - Notas de lançamento do programador -slug: Mozilla/Firefox/Releases -tags: - - Firefox - - Landing - - Lançamento - - Mozilla -translation_of: Mozilla/Firefox/Releases ---- -
{{FirefoxSidebar}}
- -

Esta página fornece hiperligações para os artigos de "Firefox X para programadores" para cada lançamento do Firefox. Estas notas deixam-no ver quais as funcionalidades que foram adicionadas e os erros eliminados em cada versão do Firefox. Tudo escrito para dar aos programadores como você a informação de que eles mais precisam. Seja bem-vindo.

- -
{{ListSubpages("",1,1,1)}}
- -
 
- -

Ufa! Isso é muito de Firefoxen!

- -

Consultar também

- - diff --git a/files/pt-pt/mozilla/index.html b/files/pt-pt/mozilla/index.html deleted file mode 100644 index 347e26f48e..0000000000 --- a/files/pt-pt/mozilla/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Mozilla -slug: Mozilla -tags: - - Aplicações - - Apps - - Avançado - - Extras - - Mozilla -translation_of: Mozilla ---- -
-

Os artigos abaixo, incluem conteúdo sobre transferência e criação de código da Mozilla. Além disso, irá encontrar artigos úteis sobre como o código funciona, como criar extras para as aplicações da Mozilla, etc.

- -

{{LandingPageListSubpages}}

-
-- cgit v1.2.3-54-g00ecf