Exemplo de notificação do ambiente de trabalho Chrome [fechado]

como é que se usa as notificações Chrome desktop ? Gostaria que usasse isso no meu próprio código.

Update : aqui está um post explicando as notificações do webkit com um exemplo.

Author: rogerdpack, 2010-02-16

9 answers

Abaixo está um exemplo de trabalho de notificações de desktop para Chrome, Firefox, Opera e Safari. Note que, por razões de segurança, a começar pelo Chrome 62, a permissão para a API de notificação pode já não ser solicitada a partir de uma iframe de origem cruzada, por isso terá de gravar este exemplo num ficheiro HTML no seu site/aplicação, e certifique-se de usar o HTTPS.

// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); 
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
});

function notifyMe() {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification('Notification title', {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "Hey there! You've been notified!",
    });

    notification.onclick = function () {
      window.open("http://stackoverflow.com/a/13328397/1269037");      
    };

  }

}
<button onclick="notifyMe()">Notify me!</button>

Estamos a usar as notificações W3C API, documentadas em MDN. Não confunda isto. com a APIdas extensões Chrome, que é diferente. As notificações de extensão do Chrome obviamente só funcionam em extensões do Chrome, não necessitam de nenhuma permissão especial do utilizador, suportam notificações de texto ricas, mas desaparecem automaticamente e o utilizador pode não reparar que foram despoletadas ). As notificações W3C funcionam em muitos navegadores (ver Suporte em caniuse ), requerem permissão do utilizador, empilham no topo da notificação anterior e não automaticamente desaparecer no cromado (fazem-no no Firefox).

Palavras finais

O apoio à notificação tem estado em fluxo contínuo, tendo várias API sido desactualizadas nos últimos três anos. Se você está curioso, verifique as edições anteriores desta resposta para ver o que costumava funcionar no Chrome, e para aprender a história de ricas notificações HTML.

Agora a última norma é em https://notifications.spec.whatwg.org/.

Há também uma chamada diferente. com os mesmos parâmetros) para criar notificações de trabalhadores de serviços, que por alguma razão, não têm acesso ao construtor Notification().

Ver também notificar.js para uma biblioteca auxiliar.

 634
Author: Dan Dascalescu, 2018-02-14 22:23:43

Verifique adesign e API Especificação (ainda é um rascunho) ou verifique a fonte a partir de (a página já não está disponível) para um exemplo simples: é principalmente uma chamada para window.webkitNotifications.createNotification.

Se quiser um exemplo mais robusto (está a tentar criar a sua própria extensão do Google Chrome, e gostaria de saber como lidar com permissões, armazenamento local e assim), verifique extensão do Gmail notificante: baixe o ficheiro crx em vez de o instalar, desaperte-o e leia a sua codigo.

 83
Author: GmonC, 2018-04-04 13:04:53

Parece que window.webkitNotifications já foi desacreditado e removido. No entanto, há uma nova API , e parece funcionar na última versão do Firefox também.

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  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
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  }

  // At last, if the user already denied any notification, and you 
  // want to be respectful there is no need to bother him any more.
}

Codepeno

 31
Author: mpen, 2014-05-31 20:41:38

Eu gosto: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples mas usa variáveis antigas, por isso a demonstração já não funciona. webkitNotifications é agora Notification.

 14
Author: Rudie, 2015-09-08 17:38:51

Notificar.js é uma embalagem em torno das novas notificações webkit. Funciona muito bem.

Http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

 4
Author: Ashley Davis, 2014-07-03 22:04:12
<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

 4
Author: Hina Halani, 2016-10-07 09:41:49
Aqui está uma boa documentação sobre APIs.

Https://developer.chrome.com/apps/notifications

E, explicação em vídeo oficial pelo Google,

Https://developers.google.com/live/shows/83992232-1001

 3
Author: Altaf Patel, 2014-04-11 06:32:48

Por alguma razão a resposta aceite não funcionou para mim, acabei por usar o seguinte exemplo:

Https://developer.chrome.com/apps/app_codelab_alarms#create-notification

function notifyMe() {

    chrome.notifications.create('reminder', {
        type: 'basic',
        iconUrl: 'icon.png',
        title: 'Don\'t forget!',
        message: 'You have  things to do. Wake up, dude!'
    }, function(notificationId) {});

}
 1
Author: Chris, 2017-04-09 07:22:56