Day 47: Push Notifications

mtee

Margaret W.N

Posted on September 1, 2020

Day 47: Push Notifications

I covered push notifications in progressive web apps, today. Here is the summary.

  • Great push notifications should be timely (Time sensitive), relevant and precise.

NB: Always ask to push notifications, after the user interacts with your page.

  • You can send push notification using either a notification API or Push API.

  • Notifications can either be persistant or non-persistant based on whether they are associated with a service worker.
    Creating a non-persistant application.

let n = new Notification('Title', {options})
Enter fullscreen mode Exit fullscreen mode

Options can be a wide range of properties starting with the body.

let n = new Notification('Title', {
 body: 'body text';
})
Enter fullscreen mode Exit fullscreen mode

Some common option include: badge, icon, image, tag(groups notifications), renotify(boolean),actions, sound etc

Creating a Persistent Notification

self.addEventlisner('notificationclick', evt => { })
Enter fullscreen mode Exit fullscreen mode

Overview of Push API

  • Configuring Push Entails serving a page with a VAPID key, checking for an existing subscription using pushManager.getSubscription(), asking for permissions from the user, if granted subscribing using pushManager.subscribe()
//subscribe a user
sw.pushManager
  .subscribe({
    userVisibleOnly: true,
    applicationServerKey:
      urlBase64ToUint8Array(publicKey)//user declared function to convert Url Base64 to Uint8 Array.
  })
  .then(subscription => { });
Enter fullscreen mode Exit fullscreen mode

And finally sending a subscription to the server.

  • Sending a Message To send a message you have to generate an encrypted message. You can use web-push-libs. Send the message to the web server and then from the web server to the browser.
  • Receiving a message To receive the message you have to handle and listen to the push event
self.addEventListener('push', evt => { })
Enter fullscreen mode Exit fullscreen mode

Then call show notifications using self.register.showNotification in the service worker and handle notification click events. It's a good practice to start with closing the notification using Notification.close().

That is all for today. As ways looking forward to the building part of it.
-Day 47_

💖 💪 🙅 🚩
mtee
Margaret W.N

Posted on September 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related