aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html')
-rw-r--r--files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html289
1 files changed, 289 insertions, 0 deletions
diff --git a/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html b/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html
new file mode 100644
index 0000000000..ca76a8b6bd
--- /dev/null
+++ b/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html
@@ -0,0 +1,289 @@
+---
+title: Utilizar a API de Notificações
+slug: Web/API/Notifications_API/Utilizar_API_Notificações
+translation_of: Web/API/Notifications_API/Using_the_Notifications_API
+---
+<p>{{APIRef("Web Notifications")}}</p>
+
+<p class="summary">The <a href="/en-US/docs/Web/API/Notifications_API">Notifications API</a> lets a web page or app send notifications that are displayed outside the page at the system level; this lets web apps send information to a user even if the application is idle or in the background. This article looks at the basics of using this API in your own apps.</p>
+
+<p>{{AvailableInWorkers}}</p>
+
+<p>Typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device brodcasts notifications.</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/10959/android-notification.png" style="display: block; height: 184px; margin: 0px auto; width: 300px;"><img alt="" src="https://mdn.mozillademos.org/files/10961/mac-notification.png" style="display: block; height: 97px; margin: 0px auto; width: 358px;"></p>
+
+<p>The system notification system will vary of course by platform and browser, but this is ok, and the Notifications API is written to be general enough for compatibility with most system notification systems.</p>
+
+<h2 id="Exemplos">Exemplos</h2>
+
+<div class="column-container">
+<div class="column-half">
+<p>One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many real examples of this now exist, such as <a href="https://slack.com/">Slack</a>.</p>
+
+<p>We've written a couple of real world demos to give more of an idea of how web notifications can be used:</p>
+
+<ul>
+ <li><strong>To-do list</strong>: This is a simple to-do list app that stores data locally using <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and notifies users when tasks are due using system notifications. <a href="https://github.com/mdn/to-do-notifications/tree/gh-pages">Download the To-do list code</a>, or <a href="http://mdn.github.io/to-do-notifications/">view the app running live</a>.</li>
+ <li><strong>Emogotchi</strong>: A rather silly parody of Tamagotchi, in which you have to keep your Emo miserable otherwise you lose the game. This uses system notifications to tell you how well you are doing, and to complain at you, ALL THE TIME. <a href="https://github.com/mdn/emogotchi">Download the Emogotchi code</a>, or <a href="http://mdn.github.io/emogotchi/">view it running live</a>.</li>
+</ul>
+</div>
+
+<div class="column-half">
+<p style="text-align: center;"><img alt="" src="https://mdn.mozillademos.org/files/10963/emogotchi.png" style="max-width: 300px; width: 70%;">.</p>
+</div>
+</div>
+
+<h2 id="Solicitar_permissão">Solicitar permissão</h2>
+
+<p>Before an app can send a notification, the user must grant the application the right to do so. This is a common requirement when an API tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.</p>
+
+<h3 id="Verificação_do_estado_da_permissão_atual">Verificação do estado da permissão atual</h3>
+
+<p>You can check to see if you already have permission by checking the value of the {{domxref("Notification.permission")}} read only property. It can have one of three possible values:</p>
+
+<dl>
+ <dt><code>default</code></dt>
+ <dd>The user hasn't been asked for permission yet, so notifications won't be displayed.</dd>
+ <dt><code>granted</code></dt>
+ <dd>The user has granted permission to display notifications, after having been asked previously.</dd>
+ <dt><code>denied</code></dt>
+ <dd>The user has explicitly declined permission to show notifications.</dd>
+</dl>
+
+<h3 id="Obter_permissão">Obter permissão</h3>
+
+<p>If permission to display notifications hasn't been granted yet, the application needs to use the {{domxref("Notification.requestPermission()")}} method to request this form the user. In its simplest form, as used in the <a href="https://github.com/mdn/emogotchi/blob/gh-pages/main.js#L54">Emogotchi demo</a>, we just include the following:</p>
+
+<pre class="brush: js">Notification.requestPermission();</pre>
+
+<p>The method also optionally accepts a callback function that is called once the user has responded to the request to display permissions (as seen in the second <code>else ... if</code> block below.) Commonly, you'll ask for permission to display notifications when your app is first initialized, and before trying to instantiate any. If you wanted to be really thorough, you could use a construct like the following (see <a href="https://github.com/mdn/to-do-notifications/blob/gh-pages/scripts/todo.js#L305-L344">To-do List Notifications</a>):</p>
+
+<pre class="brush: js">function notifyMe() {
+ // Let's check if the browser supports notifications
+ if (!("Notification" in window)) {
+ alert("This browser does not support system notifications");
+ }
+
+ // Let's check whether notification permissions have already been granted
+ else if (Notification.permission === "granted") {
+ // If it's okay let's create a notification
+ var notification = new Notification("Hi there!");
+ }
+
+ // Otherwise, we need to ask the user for permission
+ else if (Notification.permission !== 'denied') {
+ Notification.requestPermission(function (permission) {
+ // If the user accepts, let's create a notification
+ if (permission === "granted") {
+ var notification = new Notification("Hi there!");
+ }
+ });
+ }
+
+ // Finally, if the user has denied notifications and you
+ // want to be respectful there is no need to bother them any more.
+}</pre>
+
+<div class="note">
+<p><strong>Note:</strong> Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the <code>load</code> event handler (see <a href="https://code.google.com/p/chromium/issues/detail?id=274284" title="https://code.google.com/p/chromium/issues/detail?id=274284">issue 274284</a>).</p>
+</div>
+
+<h3 id="Permissões_de_manifesto_do_Firefox_OS">Permissões de manifesto do Firefox OS</h3>
+
+<p>Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your <code>manifest.webapp</code> file when including it in an Firefox OS app:</p>
+
+<pre>"permissions": {
+ "desktop-notification": {
+ "description": "Needed for creating system notifications."
+ }
+},
+"messages": [{"notification": "path/to/your/index.html"}]
+
+</pre>
+
+<div class="note">
+<p><strong>Note</strong>: When an application is installed, you shouldn't need to {{anch("Getting permission","explicitly request permission")}}, but you will still need the permissions and messages entries above for the notifications to be fired.</p>
+</div>
+
+<h2 id="Criação_de_uma_notificação">Criação de uma notificação</h2>
+
+<p>Creating a notification is easy; just use the {{domxref("Notification")}} constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an {{domxref("Notification.icon","icon")}} or a text {{domxref("Notification.body","body")}}.</p>
+
+<p>For example, in the <a href="https://github.com/mdn/emogotchi/blob/gh-pages/main.js#L101-L117">Emogotchi example</a> we have two functions that can be called when a notification needs to be fired; which one is used depends on whether we want a set notification, or a notification that includes random body content:</p>
+
+<pre class="brush: js">function spawnNotification(theBody,theIcon,theTitle) {
+ var options = {
+ body: theBody,
+ icon: theIcon
+ }
+ var n = new Notification(theTitle,options);
+ setTimeout(n.close.bind(n), 5000);
+}
+
+function randomNotification() {
+ var randomQuote = quoteChooser();
+ var options = {
+ body: randomQuote,
+ icon: 'img/sad_head.png',
+ }
+
+ var n = new Notification('Emogotchi says',options);
+ setTimeout(n.close.bind(n), 5000);
+}</pre>
+
+<h2 id="Fechar_notificações">Fechar notificações</h2>
+
+<p>Firefox and Safari close notifications automatically after a few moments (around four seconds). This may also happen at the operating system level. Some browsers don't however, such as Chrome. To make sure that the notifications close in all browsers, at the end of the above functions, we call the {{domxref("Notification.close")}} func<code>tion</code> inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind()</a></code> to make sure the <code>close()</code> call is associated with the notification.</p>
+
+<pre class="brush: js">setTimeout(n.close.bind(n), 5000);
+</pre>
+
+<div class="note">
+<p><strong>Note</strong>: When you receive a "close" event, there is no guarantee that it's the user who closed the notification. This is in line with the specification, which states: "When a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run."</p>
+</div>
+
+<h2 id="Eventos_de_notificação">Eventos de notificação</h2>
+
+<p>The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:</p>
+
+<dl>
+ <dt>{{event("click")}}</dt>
+ <dd>Triggered when the user clicks on the notification.</dd>
+ <dt>{{event("error")}}</dt>
+ <dd>Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.</dd>
+</dl>
+
+<p>These events can be tracked using the {{domxref("Notification.onclick","onclick")}} and {{domxref("Notification.onerror","onerror")}} handlers. Because {{domxref("Notification")}} also inherits from {{domxref("EventTarget")}}, it's possible to use the {{domxref("EventTarget.addEventListener","addEventListener()")}} method on it.</p>
+
+<p>There are also two other events that used to be listed in the spec, but were recently removed. These may still work in browsers for a while, but they should be treated as obsolete and not used:</p>
+
+<dl>
+ <dt>{{event("close")}}</dt>
+ <dd>Triggered once the notification is closed.</dd>
+ <dt>{{event("show")}}</dt>
+ <dd>Triggered when the notification is displayed to the user.</dd>
+</dl>
+
+<h2 id="Substituir_notificações_existentes">Substituir notificações existentes</h2>
+
+<p>It is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one.</p>
+
+<p>To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already <span style="line-height: 1.5;">been </span><span style="line-height: 1.5;">displayed, the previous notification is closed and the new one is displayed.</span></p>
+
+<h3 id="Exemplo_de_etiqueta">Exemplo de etiqueta</h3>
+
+<p>Assume the following basic HTML:</p>
+
+<pre class="brush: html">&lt;button&gt;Notify me!&lt;/button&gt;</pre>
+
+<p>It's possible to handle multiple notifications this way:</p>
+
+<pre class="brush: js">window.addEventListener('load', function () {
+ // At first, let's check if we have permission for notification
+ // If not, let's ask for it
+ if (window.Notification &amp;&amp; Notification.permission !== "granted") {
+ Notification.requestPermission(function (status) {
+ if (Notification.permission !== status) {
+ Notification.permission = status;
+ }
+ });
+ }
+
+ var button = document.getElementsByTagName('button')[0];
+
+ button.addEventListener('click', function () {
+ // If the user agreed to get notified
+ // Let's try to send ten notifications
+ if (window.Notification &amp;&amp; Notification.permission === "granted") {
+ var i = 0;
+ // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
+ var interval = window.setInterval(function () {
+ // Thanks to the tag, we should only see the "Hi! 9" notification
+ var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+ if (i++ == 9) {
+ window.clearInterval(interval);
+ }
+ }, 200);
+ }
+
+ // If the user hasn't told if he wants to be notified or not
+ // Note: because of Chrome, we are not sure the permission property
+ // is set, therefore it's unsafe to check for the "default" value.
+ else if (window.Notification &amp;&amp; Notification.permission !== "denied") {
+ Notification.requestPermission(function (status) {
+ if (Notification.permission !== status) {
+ Notification.permission = status;
+ }
+
+ // If the user said okay
+ if (status === "granted") {
+ var i = 0;
+ // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time.
+ var interval = window.setInterval(function () {
+ // Thanks to the tag, we should only see the "Hi! 9" notification
+ var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+ if (i++ == 9) {
+ window.clearInterval(interval);
+ }
+ }, 200);
+ }
+
+ // Otherwise, we can fallback to a regular modal alert
+ else {
+ alert("Hi!");
+ }
+ });
+ }
+
+ // If the user refuses to get notified
+ else {
+ // We can fallback to a regular modal alert
+ alert("Hi!");
+ }
+ });
+});</pre>
+
+<p>See the live result below:</p>
+
+<p>{{ EmbedLiveSample('Tag_example', '100%', 30) }}</p>
+
+<h2 id="Receber_notificação_de_cliques_nas_notificações_da_aplicação">Receber notificação de cliques nas notificações da aplicação</h2>
+
+<p>When a user clicks on a notification generated by an app, you will be notified of this event in two different ways, depending on the circumstance:</p>
+
+<ol>
+ <li>A click event if your app has not closed or been put in the background between the time you create the notification and the time the user clicks on it.</li>
+ <li>A <a href="/en-US/docs/Web/API/Navigator/mozSetMessageHandler">system message</a> otherwise.</li>
+</ol>
+
+<p>See <a href="https://github.com/mozilla/buddyup/commit/829cba7afa576052cf601c3e286b8d1981f93f45#diff-3">this code snippet</a> for an example of how to deal with this.</p>
+
+<h2 id="Especificações">Especificações</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('Web Notifications')}}</td>
+ <td>{{Spec2('Web Notifications')}}</td>
+ <td>Living standard</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2>
+
+<p>{{page("/en-US/Web/API/Notification","Browser compatibility")}}</p>
+
+<h2 id="Consultar_também">Consultar também</h2>
+
+<ul>
+ <li><a href="/en-US/Apps/Build/User_notifications">Referência das notificações do utilizador</a></li>
+ <li><a href="/en-US/Apps/Build/User_notifications/Notifying_users_via_the_Notification_and_Vibration">Notificação dos utilziadores via APIs de Notificação e Vibração</a></li>
+ <li>{{ domxref("Notificação") }}</li>
+</ul>