Sridhar Ratnakumar Sridhar Ratnakumar - 1 month ago 19
Javascript Question

Chrome desktop notification example

Is there an open-source example that demonstrates Chrome desktop notifications? I'd like that use that in my own code.

Update: Here's a blog post explaining webkit notifications with an example.

Answer

Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari.
Try it live on JSBin.

// 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>

We're using the W3C Notifications API, documented at MDN. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, don't require any special permission from the user, support rich text notifications, but disappear automatically and the user may not notice they have been triggered). W3C notifications work in many browsers (see support on caniuse), require user permission, stack on top of the previous notification and don't automatically disappear in Chrome (they do in Firefox).

Final words

Notification support has been in continuous flux, with various APIs being deprecated over the last three years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.

Now the latest standard is at https://notifications.spec.whatwg.org/.

There's also a different call (though with the same parameters) to create notifications from service workers, which for some reason, don't have access to the Notification() constructor.

See also notify.js for a helper library.

Comments