}

Utilizing Push Notifications in a Progressive Web App (PWA)

A push notification is gentle nudge from your website to re-engage with a user by delivering a short message that pops up on the user's device. The message can be triggered locally by the open application or can be "pushed" from the server to the user even when the app is not running. A service worker is required to handle the push and utilizes the Web Push Protocol. The end-user must opt-in to allow your app to send push notifications typically through a subscribe/unsubscribe button.

screenshot of popup on pushjs.org

1. Determine if "Push" messaging is supported in the browser. All the modern browsers support push except for Safari on ios.

if ('serviceWorker' in navigator && 'PushManager' in window){

2. Most browsers require an application server key to subscribe to push messaging, known as VAPID keys. Application server keys are a public and private key pair that is unique to your application. The public key can be shared freely, but the private key should be kept secret to your application.

$ npm install web-push --save
$ ./node_modules/.bin/web-push generate-vapid-keys

3. Provide a button allowing the user to subscribe to "push" messaging.

Notification.requestPermission().then(function(result) {

if ((result === 'denied') || (result === 'default')) {

//Permission wasn't granted.

return;

}

const applicationServerKey = urlB64ToUint8Array('...PublicKey...');
srvWorker.pushManager.subscribe

({

userVisibleOnly: true,
applicationServerKey: applicationServerKey
})

});

4. The user subscription data should be saved to a backend database.

5. Use the "push" event handler and the showNotification method to display the push notification.

self.addEventListener ('push', function(event) {
//Push Received

const title = 'Push PWAService';
const options = {
body: 'This is a push notification from my PWA.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil (self.registration.showNotification (title, options) );
});

6. Allow the user to click on the notification and trigger an action.

self.addEventListener ('notificationclick', function(event)

{
//SW Notification click Received.
event.notification.close(); //close notification
event.waitUntil(

//open a window
clients.openWindow('https://www.learningtree.com/webinars/')
);
});

7. Allow the user to unsubscribe to "push" messaging.

swRegistration.pushManager.getSubscription()
.then (function(subscription) {
if (subscription) {
return subscription.unsubscribe();
}
})
.catch (function(error) {
console.log ('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn(); //update button to allow "Enable Push"
});

8. Update the backend database with user unsubscribe data.