Show Menu
Cheatography

Adding Push Notifications to a Web App Cheat Sheet by [deleted]

Setup

Clone repo
Install webserver
Select app folder from cloned repo in webserver
Always update the service worker
Open DevTools (Right Click > Inspect) -> Applic­ation -> Service Workers -> Update on Reload
 

Register a Service Worker

 navigator.serviceWorker.register('sw.js')   .then(function(swReg) {     console.log('Service Worker is registered', swReg);      swRegistration = swReg;   })

Subscribe the user

swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

 const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  })
  .then(function(subscription) {
    updateSubscriptionOnServer(subscription);

    isSubscribed = true;

  })
  });

Get Applic­ation Server Keys

Generate public­/pr­ivate keys
Insert them into your applic­ation
 

Handle Permission Denied

if (Notification.permission === 'denied') {
    pushButton.textContent = 'Push Messaging Blocked.';
    pushButton.disabled = true;
    updateSubscriptionOnServer(null);
    return;
  }

  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;

Handle a Push Event

self.addEventListener('push', function(event) {
  console.log('[Service Worker] Push Received.');
  console.log(
[Service Worker] Push had this data: "${event.data.text()}"
);   const title = 'Push Codelab';   const options = {     body: 'Yay it works.',     icon: 'images/icon.png',     badge: 'images/badge.png'   };   event.waitUntil(self.registration.showNotification(title, options)); });

Notifi­cation click

self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');

  event.notification.close();

  event.waitUntil(
    clients.openWindow('https://developers.google.com/web/')
  );
});

Sending push messages

Unsubs­cribe the user

pushButton.addEventListener('click', function() {
  pushButton.disabled = true;
  if (isSubscribed) {
    unsubscribeUser();
  } else {
    subscribeUser();
  }
});

swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    if (subscription) {
      return subscription.unsubscribe();
    }
  })
  .then(function() {
    updateSubscriptionOnServer(null);

    console.log('User is unsubscribed.');
    isSubscribed = false;

    updateBtn();
  });
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          More Cheat Sheets by [deleted]