15

I have a web application. I want to use the HTML 5 inbuilt notifications API to do push notifications from the server when the user is on a particular page. Is it possible?

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
Vickrant
  • 1,000
  • 2
  • 8
  • 15

2 Answers2

17

You can do real push notifications with Web apps today in Chrome using Service Workers and PushManager from the W3C Push API.

See the article Push Notifications on the Open Web for a step-by-step how-to and code snippets you can use. Here’s a diagram from that article that explains what the UI around it looks like.

enter image description here

An implementation of the Push API has already landed in Firefox too; it’s targeted for shipping in November 2015 in Firefox 42. And Microsoft has indicated that the Push API is also under consideration for implementation in Edge team as well.

Below is a simple code example, borrowed from MDN.

this.onpush = function(event) {
  console.log(event.data);
}

navigator.serviceWorker.register('serviceworker.js').then(
    function(serviceWorkerRegistration) {
        serviceWorkerRegistration.pushManager.subscribe().then(
            function(pushSubscription) {
                console.log(pushSubscription.subscriptionId);
                console.log(pushSubscription.endpoint);
            }, function(error) {
                console.log(error);
            }
        );
    }
);
Black
  • 12,789
  • 26
  • 116
  • 196
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
  • 5
    The client side is easy. What about the server side? Isn't that the meat of the question? – Pacerier Mar 03 '17 at 07:58
  • Is the google cloud messaging (firebase) approach only considered for chrome or does it also work for firefox? – Vetterjack May 16 '17 at 10:29
  • @Vetterjack only chrome and android I believe – A Friend Apr 16 '18 at 21:23
  • 1
    The tutorial here has information about how to handle the server side: https://www.html5rocks.com/en/tutorials/websockets/basics/ It involves using a technology that can handle large numbers of open connections at once. – raphael75 May 10 '19 at 13:16
  • You are only showing half part of the answer. You forgot server side – Black Dec 16 '19 at 09:26
4

It depends on what you want to achieve:

  • if you want to display a push notifications to the user while is surfing your website you can use the Web Notifications API, to give the notification a "native" style; you may also use a technology like SSE or WebSockets to push the notification from your server to the client
  • if you want off-site push notifications (that are delivered even when the user is not on your website) you should use a combination of Service Workers and Push API to trigger the offline event and use the Notifications API to display the notification (see my answer)
collimarco
  • 29,854
  • 31
  • 89
  • 120