Push notifications in Web Apps via Service Workers

Posted on Jun 17, 2017

Push notifications in Web Apps via Service Workers

Push notifications, a way in which content finds the user instead of other way around. Once a feature only known for native mobile applications, have found a way to all kind of web apps, progressive web apps.

First of all, let’s answer the most obvious question, what are push notifications?

According to Wikipedia,

A push notification is a message that is “pushed” from backend server or application to user interface, e.g. (But not limited to) mobile applications and desktop applications.

Well, this makes it quite clear, so now the second question, why via service workers?

Service workers are a great way to run some script in the background and not putting the load on your main business logic running on front-end. I am not going to explain too much about Service Workers in this post, as I have written a separate blog for that. You can check that here.

Let’s get back to our question, why service workers, well I would say because your app does not have to be open in the browser, to get the notification. I mean that’s the real purpose of push notifications, notify the user about the content of your application.

Before I show how to add push notifications in your application, I would like to explain how they work. The flow is simple, your application server tells Google Cloud Messaging (GCM) server that there is something new content and GCM server then awakens the service worker which generates the push notification.

Push notifications service workers

 

Now, I’m gonna show today how to add push notifications using active service workers. So, let’s start, shall we?

Register Service Worker

 


if ('serviceWorker' in navigator && 'PushManager' in window) {
  navigator.serviceWorker.register('software-worker.js')
  .then(function(reg) {
    registration = reg;
  })
  .catch(function(error) {
    return;
  });
} else {
  // Well Service Worker or Push Notifications 
  // aren't supported 
  // yet in your browser
}

Here is what we did in above snippet of code:
1. Checking if the browser supports service worker and push notifications.
2. Handle accordingly if the browser doesn’t support them.
3. If they do, register the service worker file and get the registration object.
I hope all clear so far.

Subscribe to Notifications from client

 


registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: UInt8array Key
  })
  .then(function(subscription) {
    if (subscription) {
       // User is already subscribed
    }
  })
  .catch(function(err) {
    // User have declined request for Push notifications
  });

This is what I am doing above:
1. Using push manager service create the subscription.
2. You need to have applicationServerKey for this.
3. Once got the subscription object, send it to server.

Note: userVisibleOnly: true must be true, otherwise you will get an error in your browser console.

Push notifications handler

 


self.addEventListener('push', function(event) {
  event.waitUntil(
    self.registration.showNotification(Title, {
      body: Body,
      icon: Icon
    })
  );
});

It will trigger every time, your service worker will be awakened by GCM server.

And that’s it, you have an active service worker that will push notifications to the user every time GCM server will call it.

This post’s scope was only to cover the use of service workers in push notifications, let me know if you also want me cover topics like GCM and push notifications in Google Chrome extension.