Desktop notifications in Chrome with Javascript

I have an application in which I need to send notifications to the user, and I would like these to appear on the desktop, as the example below. Is it possible to do it with Javascript? If so, how? I didn't want to use alert(), as I find it inconvenient. It does not need to work in other browsers.

Example of "Checker Plus"

example

Author: Calebe Oliveira, 2014-01-17

1 answers

There is a functionality being planned for HTML5 called Notification (currently only supported [on desktop] by Firefox, Chrome and Safari):

Notification.requestPermission(/* opcional: callback */);

...

var notification = new Notification("Título", {
    icon: 'http://i.stack.imgur.com/dmHl0.png',
    body: "Texto da notificação"
});
notification.onclick = function() {
    window.open("http://stackoverflow.com");
}

Example in jsFiddle .


Webkit-specific solution

You can do it through window.webkitNotifications, as the example below:

var havePermission = window.webkitNotifications.checkPermission();
if (havePermission == 0) {
  // 0 is PERMISSION_ALLOWED
  var notification = window.webkitNotifications.createNotification(
    'http://i.stack.imgur.com/dmHl0.png',
    'Chrome notification!',
    'Here is the notification text'
  );

  notification.onclick = function () {
    window.open("https://stackoverflow.com/a/13328397/1269037");
    notification.close();
  }
  notification.show();
} else {
    window.webkitNotifications.requestPermission();
}

Example in jsFiddle . When clicking for the first time, the browser will ask the user for permission to display notifications. After accepted, future clicks will display the notification.

Note: according to chromium'S API (base of Google Chrome, for those who do not know), the method requestPermission it needs to be called in response to a user action, otherwise it will have no effect.

This method should only be called while handling a user gesture; in other circumstances it will have no effect.

However, once permission has been granted, you can call createNotification whenever you want (maybe in response to a polling on the server, or a message from a WebSocket, etc). requestPermission also accepts a callback, If you want to be notified when the user accepts/declines the permission.

There is also a feature called rich notifications - which greatly extends the types of content supported in the notification - but I do not know it in detail. link to the API .

Sample code source: this answer in Soen

 25
Author: mgibsonbr, 2017-05-23 12:37:28