DEV Community

Margaret W.N
Margaret W.N

Posted on

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_

Top comments (2)

Collapse
 
miqueasgutierrez profile image
miqueasgutierrez

Good information, another good option would be integrating INDIGITALL, it allows you to send Notifications with an animated image, Segmented, Geolocated and many more functions, it is great. It also integrates its API
Here you can see the installation guide for your platform:
docs.indigitall.com/

Collapse
 
mtee profile image
Margaret W.N

Awesome! Let me check it out. Thank you for sharing.