Taqi Taqi - 2 months ago 66
Javascript Question

Web Push Notification for Chrome

How to create Web Chrome Notifications ?
I have been searching for how to create a web push chrome notification using payload and after a decent R&D, i would like to share my code with you all.

Answer
                         Client Side Code: 
    main.js

    function base64UrlToUint8Array(base64UrlData) {
      const padding = '='.repeat((4 - base64UrlData.length % 4) % 4);
      const base64 = (base64UrlData + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');
      const rawData = atob(base64);
      const buffer = new Uint8Array(rawData.length);
      for (let i = 0; i < rawData.length; ++i) {
        buffer[i] = rawData.charCodeAt(i);
      }
      return buffer;
    }
    (function() {
      if (!('serviceWorker' in navigator)) {
        return;
      }
      return navigator.serviceWorker.register('sw.js')
      .then(function(registration) {
        console.log('service worker registered');
        return navigator.serviceWorker.ready;
      })
      .then(function(reg) {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(e) {
          window.document.title = e.data;
        }
        reg.active.postMessage('setup', [channel.port2]);
        var subscribeOptions = { userVisibleOnly: true };
        // Figure out the vapid key
        var searchParam = window.location.search;
        vapidRegex = searchParam.match(/vapid=(.[^&]*)/);
        if (vapidRegex) {
          // Convert the base 64 encoded string
          subscribeOptions.applicationServerKey = base64UrlToUint8Array(vapidRegex[1]);
        }
        console.log(subscribeOptions);
        return reg.pushManager.subscribe(subscribeOptions);
      })
      .then(function(subscription) {
        console.log(JSON.stringify(subscription));
        window.subscribeSuccess = true;
        window.testSubscription = JSON.stringify(subscription);
      })
      .catch(function(err) {
        window.subscribeSuccess = false;
        window.subscribeError = err;
      });
    })();


    sw.js

    'use strict';

    let port;
    let pushMessage;

    console.log('Started', self);

    self.addEventListener('install', function (event) {
      self.skipWaiting();
      console.log('Installed', event);
    });

    self.addEventListener('activate', function (event) {
      console.log('Activated', event);
    });

    self.addEventListener('push', function (event) {
      if (event.data) {
        console.log(event.data);
      }
      var payload = event.data ? event.data.text() : 'no payload';

      event.waitUntil(
        self.registration.showNotification('Web Push Notification ', {
          body: payload,
          icon: 'images/abc.png',
        }));
    });

    self.addEventListener('notificationclick', function(event) {
      console.log('Notification click: tag', event.notification.tag);

      event.notification.close();
      var url = 'http://www.google.com/';

      event.waitUntil(
        clients.matchAll({
          type: 'window'
        })
        .then(function(windowClients) {
          console.log('WindowClients', windowClients);
          for (var i = 0; i < windowClients.length; i++) {
            var client = windowClients[i];
            console.log('WindowClient', client);
            if (client.url === url && 'focus' in client) {
              return client.focus();
            }
          }
          if (clients.openWindow) {
            return clients.openWindow(url);
          }
        })
      );
    });

    .................................................................................
                            SERVER SIDE CODE:
    routers/notifications.js

    var express = require('express');
    var router = express.Router();
    var webPush = require('web-push');
    var gcmUrl = "https://android.googleapis.com/gcm/send/";

    //this key is coming from gcm project
    var GCM_API_KEY = "AIzaSyAI2OM3My5E8uulEGtQn31zfydBlCjhezZZWlpE";

    router.get('/', function (req, res, next) {
    res.send('Hello');
    })
    webPush.setGCMAPIKey(GCM_API_KEY);
    router.post('/', function (req, res, next) {
      var payload = req.body;
      console.log(payload);

      gcmUrl =  "https://android.googleapis.com/gcm/send/"+req.body.registrationId;

      console.log('sending request to GCM');

      webPush.sendNotification(gcmUrl, {
        RegistrationID: req.body.registrationId,
        TTL: req.body.ttl,
        payload: req.body.payload,
        userPublicKey: req.body.key,
        userAuth: req.body.authSecret,
      })
          .then(function (gcmResponse) {
          console.log('gcm: ', gcmResponse);
          res.sendStatus(201);
        }).catch(function (gcmError) {
          console.error("error frm gcm");
          console.log(gcmError);
        });

    });


    module.exports = router;
.................................................................................
                                   Sending Request:
I used postman to send notification.

{
    "ttl" : "5",
     "payload" :"Your Request #123 is accepted" ,
     "key" : "BBqMWJxSWFFcnvpowevnskdhdX0im4nADVSj9F_53xhxahcz-dnnR8wZv44o=",
     "authSecret" : "elOOVcwciiaaavkYiDA==",
     "registrationId": "doPVnhn3Ymc:APA91bFx_2tyfKs2xbpaocnakdrzdjS0ED9okiNEz-jECb3lC43kTqfltBZ54prNgtH3P_mBaDs5JOEQihhZld-E-vggxaUVUhyphe-oSoCE"
 } 
Comments