Chrome desktop notification example [closed] Chrome desktop notification example [closed] google-chrome google-chrome

Chrome desktop notification example [closed]


In modern browsers, there are two types of notifications:

  • Desktop notifications - simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds
  • Service Worker notifications - a bit more complicated, but they can work in the background (even after the page is closed), are persistent, and support action buttons

The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.


Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost:// or HTTPS.

// request permission on page loaddocument.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>