Handling Web Push Notifications

Persistent Mobile Foundation Platform provides extended support for Push Notifications, which is now available for Web.

Installation

Perform the following steps to install web push SDK.

  1. Run npm i ibm-mfp-web-push at the root of your project.

  2. Register ServiceWorker with your web app. Copy MFPPushServiceWorker.js from node_modules/ibm-mfp-web-push to your public assets directory.

  3. Open your index.html file and copy & paste the following code inside the head tag.
     	<script>
         if (navigator.serviceWorker) {
             navigator.serviceWorker.register(<PATH-TO-COPIED-SERVICE-WORKER-FILE>).then(function(reg) {
                 window.pushReg = reg;
                 if (reg.installing) {
                     console.info('Service worker installing');
                 } else if (reg.waiting) {
                     console.info('Service worker installed');
                 } else if (reg.active) {
                     console.info('Service worker active');
                 }
                 if (!(reg.showNotification)) {
                     console.info('Notifications aren\'t supported on service workers.');
                 }
                 // Check if push messaging is supported
                 if (!('PushManager' in window)) {
                     console.info("Push messaging isn't supported.");
                 }
    
                 if (Notification.permission === 'denied') {
                     console.info('The user has blocked notifications.');
                 }
             }).catch(err => {
                 console.error(JSON.stringify(err));
             });
         } else {
             console.info("Service workers aren't supported in this browser.");
         }
     </script>
    
  4. Create a manifest.json file under the same assets directory where you put MFPPushServiceWorker.js and copy the following snippet to it.
      {
    		"name": "<APP-NAME>",
    		"gcm_sender_id": "<YOUR-FCM-SENDER-ID-HERE>"
      }
    
  5. Link the created manifest.json to your index.html as follows.
     	<link rel="manifest" href="<PATH-TO-PUBLIC-ASSETS-DIRECTORY>/manifest.json">
    

You are now ready to start working with Web Push APIs.

Using Persistent Mobile Foundation Web Push SDK

  • Add the import statement to import Web Push SDK APIs. import MFPPush from 'ibm-mfp-web-push';

  • Initialize Web Push SDK.
      var pushInitOptions = {
      	appId: "com.push.app",
      	serverUrl:"https://mfp-server-url.com",
      	safariWebsitePushId:"web.com.mfp-server-url"
      };
      MFPPush.initialize(pushInitOptions);
    

    Here,

    • appId - Application ID registered with Persistent Mobile Foundation Server.
    • serverUrl - the URL to your Persistent Mobile Foundation Server.
    • safariWebsitePushId - [optional] if Safari Platform needs to be supported.
  • Register Device.
      MFPPush.registerDevice().then(res => {
      	console.log("register");
      	alert("Successfully Registered Device...");
      }).catch(err => {
      	console.log("register");
      	console.log("Registration Failed" + err);
      });
    
  • Un-registering Device.
      MFPPush.unregisterDevice().then(res => {
      	console.log("register");
      	alert("Successfully Un-registered Device...");
      }).catch(err => {
      	console.log("register");
      	console.log("Unregistration Failed" + err);
      });
    
  • Subscribing to a Tag.
      MFPPush.subscribe("offers").then((res) => {
      	console.log("subscribe");
      	alert("Subscribed successfully...");
      })
      .catch((err) => {
      	console.log("subscribe");
      	console.log(JSON.stringify(err));
      });
    
  • Unsubscribing from a Tag.
      MFPPush.unsubscribe("offers").then((res) => {
      	console.log("unsubscribe");
      	alert("You are now unsubscribed from 'offers'. Sorry to see you go! :(");
      })
      .catch((err) => {
      	console.log("unsubscribe");
      	console.log(JSON.stringify(err));
      });
    
  • Retrieve available Tags.

      MFPPush.retrieveAvailableSubscriptions().then((res) => {
        	console.log("availableTags");
        /**
        * res.tags is an array of tags
        */
        	var result = "Available Tags are: \n\n";
        	for(var i in res.tags) {
        	result +=  "-> ";
        	result += res.tags[i].name + "\n";
        	}
        alert(result)    
      })
      .catch((err) => {
        	console.log("availableTags");
        	console.log(JSON.stringify(err));
      });
    
  • Retrieve active Subscriptions.

      MFPPush.retrieveActiveSubscriptions().then((res) => {
        	console.log("currentSubscriptions");
        /**
        * res.subscriptions is an array of tags
        */
        	var result = "Current subscriptions: \n\n";
        	for(var i in res.subscriptions) {
        	result +=  "-> ";
        	result += res.subscriptions[i].tagName + "\n";
        	}
        	alert(result);
      })
      .catch((err) => {
        	console.log("currentSubscriptions");
        	console.log(JSON.stringify(err));
      });
    

Setting up proxy for Persistent Mobile Foundation Web Push SDK:

In your web app, you need to provide proxy configuration. An example for the same is given below.

Using nodejs, expressjs, and http-proxy-middleware.

const proxy = require("http-proxy-middleware");
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "build")));

app.use(
  proxy("/mfp/api/imfpush/", {
    target:
      "https://mfp-server-url.com/",
    changeOrigin: true,
    pathRewrite: function (path, req) {
      console.log("Rewrite in /mfp/api/imfpush/: ", path);
      return path.replace("/mfp/api", "");
    },
  })
);
app.use(
  proxy("/mfp/api", {
    target:
      "https://mfp-server-url.com/",
    changeOrigin: true,
    pathRewrite: function (path, req) {
      console.log("Rewrite in /mfp/api: ", path);
      return path;
    },
  })
);

If you are using something else than what is shown in the above example, basically your proxy needs to intercept calls as below.

  1. From /mfp/api forward these APIs as is to your PMF server URL.
  2. From /mfp/api/imfpush remove the part of the URI /mfp/api and forward the API to your PMF server URL.
Last modified on