Show Menu

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


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

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


 const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  .then(function(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;

  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: "${}");

  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.');



Sending push messages

Unsubs­cribe the user

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

  .then(function(subscription) {
    if (subscription) {
      return subscription.unsubscribe();
  .then(function() {

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


Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi


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]