424

How does one use 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.

rogerdpack
  • 50,731
  • 31
  • 212
  • 332
Sridhar Ratnakumar
  • 68,948
  • 61
  • 139
  • 172
  • 2
    I've left an [answer below](http://stackoverflow.com/a/13328513/1269037) updated as of Nov 2012, after HTML notifications became deprecated. It has an actual example like the one you were looking for. – Dan Dascalescu Nov 11 '12 at 04:15
  • 1
    Sample and article (2013): - http://www.smartjava.org/examples/notifications/ - http://www.smartjava.org/content/chrome-and-firefox-desktop-notifications Old article (2010): - http://www.html5rocks.com/en/tutorials/notifications/quick/ – Christophe Roussy Feb 12 '13 at 16:24
  • 1
    **Update**: as of 2015 websites can also send real push notifications, which are delivered even when the user is not surfing the website. Check out [this answer](http://stackoverflow.com/a/34920874/51387) – collimarco Jan 24 '16 at 13:14
  • Your blog post is broken. I am on Chrome, and it tells me I need to try Chrome. :-) – ShiningLight Apr 21 '17 at 18:59
  • 3
    All these voters for marking it as closed must be IE / Safari lovers. It is specific to browser notification and that particularly for chrome. if it so off topic then why there are so many people liking it and marking it as starred in the first place? – prash Aug 07 '18 at 03:27
  • 4
    Why off topic ? – Smart Manoj Jul 28 '19 at 11:45
  • Here is a [blog post](https://attacomsian.com/blog/desktop-notifications-javascript) that explains how to use the JavaScript `Notification` API to display desktop notifications. – attacomsian Feb 24 '20 at 21:37

8 Answers8

740

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 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. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.

W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.

Note that Chrome doesn't honor the notification icon on Linux, due to this bug.

Final words

Notification support has been in continuous flux, with various APIs being deprecated over the last 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/.

As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.

See also notify.js for a helper library.

Smart Manoj
  • 3,837
  • 2
  • 24
  • 45
Dan Dascalescu
  • 110,650
  • 40
  • 276
  • 363
90

Check the design and API specification (it's still a draft) or check the source from (page no longer available) for a simple example: It's mainly a call to window.webkitNotifications.createNotification.

If you want a more robust example (you're trying to create your own Google Chrome's extension, and would like to know how to deal with permissions, local storage and such), check out Gmail Notifier Extension: download the crx file instead of installing it, unzip it and read its source code.

alexi2
  • 4,749
  • 4
  • 29
  • 42
GmonC
  • 10,803
  • 1
  • 27
  • 37
  • Isn't there anything which works for all browsers ? – Royi Namir Aug 21 '12 at 11:32
  • @Royi, There is [a Firefox extension](https://addons.mozilla.org/en-us/firefox/addon/html-notifications/), as well as [a native Firefox implementation which is coming sooner or later](https://bugzilla.mozilla.org/show_bug.cgi?id=594543). In the case of Internet Explorer, a possible solution would be to ask users of your site to download [Chrome Frame](http://www.google.com/chromeframe), as this would be a viable solution to get notifications working. There is [some other Microsoft Solution](http://www.winrumors.com/microsoft-enables-internet-explorer-9-desktop-notifications-for-hotmail/). – 700 Software Oct 10 '12 at 20:30
  • 8
    This answer is completely obsolete by now, 4 years later. @RoyiNamir: there is the Notifications API. Check [my answer](http://stackoverflow.com/a/13328513/1269037). – Dan Dascalescu Sep 14 '15 at 08:51
  • 1
    The example link is dead. – Vinny Oct 13 '17 at 19:32
34

See also ServiceWorkerRegistration.showNotification

It appears that window.webkitNotifications has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

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!");
      }
    });
  } else {
    alert(`Permission is ${Notification.permission}`);
  }
}

codepen

mpen
  • 237,624
  • 230
  • 766
  • 1,119
  • @Miron Please take a look at the hyperlink in the first paragraph. I linked the source, and then copied the code into my answer as per SO etiquette. If MDN wasn't a wiki I might have been more explicit about who the author was, but I'm not pretending anything. – mpen Nov 17 '17 at 18:40
  • I don't see where he said he wrote it? – brandito Nov 21 '17 at 03:02
  • codepen doesn't work – Stepan Yakovenko Mar 19 '19 at 23:13
  • 1
    @StepanYakovenko Try the codepen link again. I added an extra `else` at the end to tell you what the problem is. You probably globally disabled notifications like me :\ – mpen Mar 20 '19 at 00:45
  • This doesn't work on Android Chrome any more: VM121:10 Uncaught TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. – Stepan Yakovenko Jun 29 '20 at 11:17
  • @StepanYakovenko Hmm, doesn't say it's deprecated. You sure you're using Chrome for Android, not Android Webview? – mpen Jun 29 '20 at 23:52
  • Yes, this is chrome on Android. – Stepan Yakovenko Jul 08 '20 at 14:43
14

I like: http://www.html5rocks.com/en/tutorials/notifications/quick/#toc-examples but it uses old variables, so the demo doesn't work anymore. webkitNotifications is now Notification.

Rudie
  • 46,504
  • 37
  • 126
  • 167
  • The Twitter example there no longer works. – Dan Dascalescu Nov 11 '12 at 02:56
  • You should tell http://www.html5rocks.com/en/profiles One of em must work for Twitter =) – Rudie Nov 11 '12 at 10:41
  • Heh. Hakim was the best guy to [notify](https://github.com/hakimel/reveal.js/issues/236), since I happen to [have contributed](https://github.com/hakimel/reveal.js/commits?author=dandv) to his presentation framework. – Dan Dascalescu Nov 11 '12 at 10:44
5

I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.

Probably on Opera, IE and Edge as well but I haven't tested it yet.

Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.

Get it on Bower

$ bower install js-notify

This is how it works:

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

You have to set the title but the json object as the second argument is optional.

gravmatt
  • 409
  • 6
  • 14
  • @gravmatt have you encountered an issue with Firefox where if there is more then one browser window open, the notification does not appear ? – eran otzap Feb 21 '17 at 11:57
  • @eranotzap it should work with multiple tabs. I run a project where this is no problem. but I'm not sure with multiple windows. – gravmatt Feb 21 '17 at 15:58
  • I have the same problem with multiple tabs – eran otzap Feb 21 '17 at 16:36
  • Does it work from multiple tabs in Firefox ? – eran otzap Feb 21 '17 at 16:38
  • 1
    @eranotzap I tested it now on windows and mac. I can't see the notification in any corner of the screen but I hear the sound of the notifications and on mac I get the notification in the sidebar (with multiple tabs open). Firefox is the new internet explorer. – gravmatt Feb 22 '17 at 16:27
  • @gravmatt yes it's a known issue. thanks for trying it out thought. i'll let you know If and how i solved it. – eran otzap Feb 23 '17 at 06:22
4
<!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>

Hina Halani
  • 134
  • 7
  • 1
    Please refrain from posting code-only answers. Add a bit of comments and/or explanation, so that when people read this post in the future they will understand it. – Adriaan Oct 08 '16 at 21:04
  • For this particular code snippet, it seems pretty straightforward, though. Other users could also post a follow up question on the comment, right? – frostshoxx Nov 16 '17 at 15:54
  • 1
    [JSfiddle](https://jsfiddle.net/w5h23ek0/) with the code above does not work, "Permission for the Notification API may no longer be requested from a cross-origin iframe.". However, when you open the Developer console, and enter `Notification.requestPermission();`, then `var notification = new Notification('hello', { body: "Hey there!", });` the notification shows up. – Avatar Dec 22 '17 at 11:07
  • I'm sorry, but what exactly does this answer add to mine? – Dan Dascalescu May 12 '19 at 17:07
3

Here is nice documentation on APIs,

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

And, official video explanation by Google,

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

Altaf Patel
  • 1,265
  • 1
  • 16
  • 27
  • 1
    That API only works in Chrome apps and extensions. It's different from the [Notifications API](http://stackoverflow.com/a/13328513/1269037). – Dan Dascalescu Sep 14 '15 at 08:53
3

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

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

Ashley Davis
  • 9,255
  • 7
  • 58
  • 79