diff options
Diffstat (limited to 'files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html')
-rw-r--r-- | files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html | 461 |
1 files changed, 461 insertions, 0 deletions
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..9d3c22efac --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,461 @@ +--- +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 +--- +<div>{{AddonSidebar}} +<p>Se já leu o artigo da <a href="/pt-PT/Add-ons/WebExtensions/A_sua_primeira_extensao">A sua primeira extens</a>ã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. <br> + <br> + 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. <br> + <br> + Para implementar isto, nós iremos:.</p> + +<p>To implement this, we will:</p> + +<ul> + <li><strong>define a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_action">browser action</a>, which is a button attached to the Firefox toolbar</strong>.<br> + For the button we'll supply: + <ul> + <li>an icon, called "beasts-32.png"</li> + <li>a popup to open when the button is pressed. The popup will include HTML, CSS, and JavaScript.</li> + </ul> + </li> + <li><strong>define an icon for the extension</strong>, called "beasts-48.png". This will be shown in the Add-ons Manager.</li> + <li><strong>write a content script, "beastify.js" that will be injected into web pages</strong>.<br> + This is the code that will actually modify the pages.</li> + <li><strong>package some images of the animals, to replace images in the web page</strong>.<br> + We'll make the images "web accessible resources" so the web page can refer to them.</li> +</ul> + +<p>You could visualise the overall structure of the extension like this:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13671/Untitled-1.png" style="display: block; height: 1200px; margin-left: auto; margin-right: auto; width: 860px;"></p> + +<p>It's a simple extension, but shows many of the basic concepts of the WebExtensions API:</p> + +<ul> + <li>adding a button to the toolbar</li> + <li>defining a popup panel using HTML, CSS, and JavaScript</li> + <li>injecting content scripts into web pages</li> + <li>communicating between content scripts and the rest of the extension</li> + <li>packaging resources with your extension that can be used by web pages</li> +</ul> + +<p>You can find <a href="https://github.com/mdn/webextensions-examples/tree/master/beastify">complete source code for the extension on GitHub</a>.</p> + +<p>To write this extension, you'll need Firefox 45 or newer.</p> + +<h2 id="Escrever_a_extensão">Escrever a extensão</h2> + +<p>Create a new directory and navigate to it:</p> + +<pre class="brush: bash">mkdir beastify +cd beastify</pre> + +<h3 id="manifest.json">manifest.json</h3> + +<p>Now create a new file called "manifest.json", and give it the following contents:</p> + +<pre class="brush: json">{ + + "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" + ] + +} +</pre> + +<ul> + <li>The first three keys: <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version">manifest_version</a></code>, <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name">name</a></code>, and <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version">version</a></code>, are mandatory and contain basic metadata for the extension.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description">description</a></code> and <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url">homepage_url</a></code> are optional, but recommended: they provide useful information about the extension.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons">icons</a></code> is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permissions</a></code> lists permissions the extension needs. We're just asking for the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission"><code>activeTab</code> permission</a> here.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></code> specifies the toolbar button. We're supplying three pieces of information here: + <ul> + <li><code>default_icon</code> is mandatory, and points to the icon for the button</li> + <li><code>default_title</code> is optional, and will be shown in a tooltip</li> + <li><code>default_popup</code> is used if you want a popup to be shown when the user clicks the button. We do, so we've included this key and made it point to an HTML file included with the extension.</li> + </ul> + </li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources">web_accessible_resources</a></code> lists files that we want to make accessible to web pages. Since the extension replaces the content in the page with images we've packaged with the extension, we need to make these images accessible to the page.</li> +</ul> + +<p>Note that all paths given are relative to manifest.json itself.</p> + +<h3 id="O_ícone">O ícone</h3> + +<p>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".</p> + +<p>Create the "icons" directory and save an icon there named "beasts-48.png". You could use <a href="https://github.com/mdn/webextensions-examples/blob/master/beastify/icons/beasts-48.png">the one from our example</a>, which is taken from the <a href="https://www.iconfinder.com/iconsets/free-retina-icon-set">Aha-Soft’s Free Retina iconset</a>, and used under the terms of its <a href="http://www.aha-soft.com/free-icons/free-retina-icon-set/">license</a>.</p> + +<p>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 <code>96</code> property of the <code>icons</code> object in manifest.json:</p> + +<pre class="brush: json line-numbers language-json"><code class="language-json"><span class="key token">"icons":</span> <span class="punctuation token">{</span> + <span class="key token">"48":</span> <span class="string token">"icons/beasts-48.png"</span><span class="punctuation token">,</span> + <span class="key token">"96":</span> <span class="string token">"icons/beasts-96.png"</span> +<span class="punctuation token">}</span></code></pre> + +<h3 id="O_botão_de_barra_de_ferramentas">O botão de barra de ferramentas</h3> + +<p>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".</p> + +<p>Save an icon named "beasts-32.png" in the "icons" directory. You could use <a href="https://github.com/mdn/webextensions-examples/blob/master/beastify/icons/beasts-32.png">the one from our example</a>, which is taken from the <a href="http://www.iconbeast.com/free">IconBeast Lite icon set</a> and used under the terms of its <a href="http://www.iconbeast.com/faq/">license</a>.</p> + +<p>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.</p> + +<h3 id="A_janela_(popup)">A janela (popup)</h3> + +<p>The function of the popup is to enable the user to choose one of three beasts.</p> + +<p>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:</p> + +<ul> + <li><strong><code>choose_beast.html</code></strong> defines the content of the panel</li> + <li><strong><code>choose_beast.css</code></strong> styles the content</li> + <li><strong><code>choose_beast.js</code></strong> handles the user's choice by running a content script in the active tab</li> +</ul> + +<pre class="brush: bash">mkdir popup +cd popup +touch choose_beast.html choose_beast.css choose_beast.js +</pre> + +<h4 id="choose_beast.html">choose_beast.html</h4> + +<p>The HTML file looks like this:</p> + +<pre class="brush: html"><!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> +</pre> + +<p>We have a <code><a href="/en-US/docs/Web/HTML/Element/div"><div></a></code> element with an ID of <code>"popup-content"</code> that contains an element for each animal choice. We have another <code><div></code> with an ID of <code>"error-content"</code> and a class <code>"hidden"</code>. We'll use that in case there's a problem initializing the popup.</p> + +<p>Note that we include the CSS and JS files from this file, just like a web page.</p> + +<h4 id="choose_beast.css">choose_beast.css</h4> + +<p>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 <code>class="hidden"</code>: this means that our <code>"error-content"</code> <code><div></code> will be hidden by default.</p> + +<pre class="brush: css">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; +} + +</pre> + +<h4 id="choose_beast.js">choose_beast.js</h4> + +<p>Here's the JavaScript for the popup:</p> + +<pre class="brush: js">/** + * 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); + +</pre> + +<p>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 <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript">browser.tabs.executeScript()</a></code> 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.</p> + +<p>A common reason the <code>browser.tabs.executeScript()</code> 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 <a href="https://addons.mozilla.org/">addons.mozilla.org</a> domain. If it does fail, <code>reportExecuteScriptError()</code> will hide the <code>"popup-content"</code> <code><div></code>, show the <code>"error-content"</code> <code><div></code>, and log an error to the <a href="/en-US/Add-ons/WebExtensions/Debugging">console</a>.</p> + +<p>If executing the content script is successful, we call <code>listenForClicks()</code>. This listens for clicks on the popup.</p> + +<ul> + <li>If the click was on a button with <code>class="beast"</code>, then we call <code>beastify()</code>.</li> + <li>If the click was on a button with <code>class="reset"</code>, then we call <code>reset()</code>.</li> +</ul> + +<p>The <code>beastify()</code> function does three things:</p> + +<ul> + <li>map the button clicked to a URL pointing to an image of a particular beast</li> + <li>hide the page's whole content by injecting some CSS, using the <code><a href="/en-US/Add-ons/WebExtensions/API/tabs/insertCSS">browser.tabs.insertCSS()</a></code> API</li> + <li>send a "beastify" message to the content script using the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage">browser.tabs.sendMessage()</a></code> API, asking it to beastify the page, and passing it the URL to the beast image.</li> +</ul> + +<p>The <code>reset()</code> function essentially undoes a beastify:</p> + +<ul> + <li>remove the CSS we added, using the <code><a href="/en-US/Add-ons/WebExtensions/API/tabs/removeCSS">browser.tabs.removeCSS()</a></code> API</li> + <li>send a "reset" message to the content script asking it to reset the page.</li> +</ul> + +<h3 id="O_script_de_conteúdo">O <em>script</em> de conteúdo</h3> + +<p>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:</p> + +<pre class="brush: js">(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(); + } + }); + +})(); +</pre> + +<p>The first thing the content script does is to check for a global variable <code>window.hasRun</code>: if it's set the script returns early, otherwise it sets <code>window.hasRun</code> 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.</p> + +<p>After that, the place to start is line 40, where the content script listens for messages from the popup, using the <code><a href="/en-US/Add-ons/WebExtensions/API/runtime/onMessage">browser.runtime.onMessage</a></code> API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".</p> + +<ul> + <li>if the message is "beastify", we expect it to contain a URL pointing to a beast image. We remove any beasts that might have been added by previous "beastify" calls, then construct and append an <code><a href="/en-US/docs/Web/HTML/Element/img"><img></a></code> element whose <code>src</code> attribute is set to the beast URL.</li> + <li>if the message is "reset", we just remove any beasts that might have been added.</li> +</ul> + +<h3 id="As_feras">As feras</h3> + +<p>Finally, we need to include the images of the beasts.</p> + +<p>Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from <a href="https://github.com/mdn/webextensions-examples/tree/master/beastify/beasts">the GitHub repository</a>, or from here:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/11459/frog.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"><img alt="" src="https://mdn.mozillademos.org/files/11461/snake.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"><img alt="" src="https://mdn.mozillademos.org/files/11463/turtle.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"></p> + +<h2 id="Testar_a_extensão">Testar a extensão</h2> + +<p>First, double check that you have the right files in the right places:</p> + +<pre>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</pre> + +<p>Starting in Firefox 45, you can install extensions temporarily from disk.</p> + +<p>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:</p> + +<p>{{EmbedYouTube("sAM78GU4P34")}}</p> + +<p>Open a web page, then click the icon, select a beast, and see the web page change:</p> + +<p>{{EmbedYouTube("YMQXyAQSiE8")}}</p> + +<h2 id="Programae_a_partir_da_linha_de_comando">Programae a partir da linha de comando</h2> + +<p>Pode automatizar o passo da instalação temporária utilizando a ferramenta <a href="/pt-PT/Add-ons/WebExtensions/Primeiros_passos_com_web-ext">web-ext</a>. Experimente isto:</p> + +<pre class="brush: bash">cd beastify +web-ext run</pre> +</div> |