Monthly Archives: January 2018

Progressive Web App – Add Web Push Notification

Welcome to Progressive Web App Series. If you have missed previous blog posts, please read from following links. In this blog post we will understand how to add Web Push Notification in PWA.

  1. What Are Progressive Web Apps?
  2. App shell – Progressive Web App
  3. App Manifest – Progressive Web App
  4. Progressive Web App – Service Worker

Why We Need Web Push Notification?

The best way to engage end users is through push notifications. User visits your PWA but then he didn’t come back. You can still reach to user by way of notifications. This will engage your end user. Notifications could be for multiple things. For example.

  • New content in PWA
  • Real time alerts
  • Daily trips and tricks
  • Updates like order update, invoice update etc.

PWA supports Web Push Notification just like native mobile apps. In this post we will explain how to add web push notification using Firebase.

Create Firebase Project

To create firebase project go to Firebase Console and login with your Google account. After you create project go to your project settings and get the sender id and add to your manifest file. Check the screen shot.

Web Push Notification Sender Id

Web Push Notification Sender Id

gcm_sender_id : “YOUR_SENDER_ID”

So now we have sender id. Next step is to register for push notification.

Register for Push Notification

After your service worker is registered, you can register for push notification.

 

if (‘serviceWorker’ in navigator) {
navigator.serviceWorker
.register(‘service-worker.js’)
.then(registerForPushNotification);
}

function registerForPushNotification(){
navigator.serviceWorker.ready.then(function(registration) {
if (!registration.pushManager) {
alert(‘Your browser doesn\’t support push notification.’);
return false;
}

//To subscribe `push notification` from push manager
registration.pushManager.subscribe({
userVisibleOnly: true //Always show notification when received
})
.then(function (subscription) {
console.log(subscription);
var rawKey = subscription.getKey ? subscription.getKey(‘p256dh’) : ”;
var key = rawKey ? Base64EncodeUrl(btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey)))) : ”;
var rawAuthSecret = subscription.getKey ? subscription.getKey(‘auth’) : ”;
var authSecret = rawAuthSecret ? Base64EncodeUrl(btoa(String.fromCharCode.apply(null, new      Uint8Array(rawAuthSecret)))) : ”;
console.log(“Key: ” + key);
console.log(“AuthSecret: ” + authSecret);
console.log(‘endpoint:’, subscription.endpoint);
//Save Data on Server.
})
.catch(function (error) {
alert(‘Oops, you have disabled push notificaitons. I will not be able to give       you real time updates.’)
});
});
}

function Base64EncodeUrl(str){
return str.replace(/\+/g, ‘-‘).replace(/\//g, ‘_’).replace(/\=+$/, ”);
}

function Base64DecodeUrl(str){
str = (str + ‘===’).slice(0, str.length + (str.length % 4));
return str.replace(/-/g, ‘+’).replace(/_/g, ‘/’);
}

Above functions will subscribe user for push notifications. Key, AuthSecret and endPoint, you have to save on server so that later you can use it for sending push notifications from server to your PWA application.

Also before subscribe, you can also check if user is already subscribed for notification.

registration.pushManager.getSubscription()

If user is already subscribed then you will get subscription object and just update it on server.

Here in this blog I have mentioned how to send push notification using NodeJS script.

Send Firebase Push Notification with NodeJs

Once you get notification, you have to add listener to check for notification and show it to user.

For that you have to add event listener in your service worker.

self.addEventListener(‘push’, function(event) {console.log(event);
var data = event.data.json();

var title = data.title;

var body ={
‘body’: data.message,
‘tag’: ‘PUSH’,
‘icon’: ‘images/icons/icon-32×32.png’
};

event.waitUntil(
self.registration.showNotification(title, body)
);
});

Above code will show notification in default window.