Exemple de notification Chrome desktop [fermé]

comment utiliser Chrome notifications de bureau ? J'aimerais que l'utiliser dans mon propre code.

mise à Jour : un blog , expliquant webkit notifications avec un exemple.

362
demandé sur rogerdpack 2010-02-16 10:07:49

9 réponses

ci-dessous est un exemple fonctionnel de notifications de bureau pour Chrome, Firefox, Opera et Safari. Notez que pour des raisons de sécurité, à commencer par Chrome 62, la permission pour L'API de Notification ne peut plus être demandée à partir d'une iframe , vous devrez donc sauvegarder cet exemple dans un fichier HTML sur votre site/application, et vous assurer d'utiliser 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>

nous utilisons le W3C Notifications API, documentée à MDN . Ne confondez pas cela avec l'API Chrome extensions notifications , qui est différent. Les notifications d'extension Chrome ne fonctionnent évidemment que dans les extensions Chrome, ne nécessitent aucune permission spéciale de l'utilisateur, prennent en charge les notifications de texte riche, mais disparaît automatiquement et l'utilisateur ne peut pas remarquer qu'ils ont été déclenchés ). Les notifications W3C fonctionnent dans de nombreux les navigateurs (voir la prise en charge sur caniuse ), nécessitent l'autorisation de l'utilisateur, empilent sur la notification précédente et ne disparaissent pas automatiquement dans Chrome ( ils font dans Firefox ).

mots Finals

Le soutien à la Notification

est en constante évolution, plusieurs IPA étant dépréciées au cours des trois dernières années. Si vous êtes curieux, consultez les éditions précédentes de cette réponse pour voir ce qui fonctionnait dans Chrome, et pour apprendre l'histoire de notifications HTML riches.

maintenant la dernière norme est à https://notifications.spec.whatwg.org / .

il y a aussi un appel différent (bien qu'avec les mêmes paramètres) pour créer des notifications des travailleurs des services, qui pour une raison quelconque , n'ont pas accès au constructeur Notification() .

Voir aussi notifier.js pour une bibliothèque d'aide.

634
répondu Dan Dascalescu 2018-02-14 22:23:43

cochez la case design et API Spécification (c'est toujours un brouillon) ou vérifiez la source à partir de (page plus disponible) pour un exemple simple: il s'agit principalement d'un appel à window.webkitNotifications.createNotification .

si vous voulez un exemple plus robuste (vous essayez de créer votre propre extension Google Chrome, et vous voulez savoir comment gérer les permissions, le stockage local et autres), consultez Gmail Notifier Extension : télécharger le fichier crx au lieu de l'installer, décompressez-le et lire son code source.

83
répondu GmonC 2018-04-04 13:04:53

il semble que window.webkitNotifications ait déjà été déprécié et supprimé. Cependant , il existe une nouvelle API , et il semble fonctionner dans la dernière version de Firefox ainsi.

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.
}

codepen

31
répondu mpen 2014-05-31 20:41:38

j'aime: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples mais il utilise de vieilles variables, donc la démo ne fonctionne plus. webkitNotifications est maintenant Notification .

14
répondu Rudie 2015-09-08 17:38:51

notifier.js est un wrapper autour des nouvelles notifications webkit. Il fonctionne assez bien.

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

4
répondu Ashley Davis 2014-07-03 22:04:12

j'ai fait ce simple emballage de Notification. Il fonctionne sur Chrome, Safari et Firefox.

probablement sur Opera, IE et Edge aussi mais je ne l'ai pas encore testé.

il suffit d'obtenir la notification.fichier js d'ici https://github.com/gravmatt/js-notify et mettez-le dans votre page.

Get it on Bower

$ bower install js-notify

C'est comme ça que ça marche:

notify('title', {
    body: 'Notification Text',
    icon: 'path/to/image.png',
    onclick: function(e) {}, // e -> Notification object
    onclose: function(e) {},
    ondenied: function(e) {}
  });

You doivent définir le titre mais l'objet json comme deuxième argument est optionnel.

4
répondu gravmatt 2016-01-27 13:18:36
<!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
répondu Hina Halani 2016-10-07 09:41:49

Voici une belle documentation sur APIs,

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

et, explication vidéo officielle par Google,

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

3
répondu Altaf Patel 2014-04-11 06:32:48

pour une raison quelconque, la réponse acceptée n'a pas fonctionné pour moi, j'ai fini par utiliser l'exemple suivant:

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
répondu Chris 2017-04-09 07:22:56