8.0.2020052213 • Published 4 years ago

ibm-mfp-web-push v8.0.2020052213

Weekly downloads
4
License
SEE LICENSE IN LI...
Repository
-
Last release
4 years ago

IBM MFP Web Push SDK

IBM Mobile Foundation Platform brings to you extended support for Push Notifications - now on Web.


Installation Guide:

  • Run npm i ibm-mfp-web-push at the root of your project.
  • Register ServiceWorker with your web app. Copy MFPPushServiceWorker.js from node_modules/ibm-mfp-web-push to your public assets directory.
  • 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>
  • Create a manifest.json file under the same assets directory where you put MFPPushServiceWorker.js and copy the following into it:

    {
       "name": "<APP-NAME>",
       "gcm_sender_id": "<YOUR-FCM-SENDER-ID-HERE>"
    }
  • Link the above created manifest.json to your index.html as follows:

    <link rel="manifest" href="<PATH-TO-PUBLIC-ASSETS-DIRECTORY>/manifest.json">

    That's it, you are good to start with Web Push APIs now.


Using IBM MFP Web Push SDK:

  • 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 MobileFirst Server
    • serverUrl - the URL to your MobileFirst 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 IBM MFP Web Push SDK:

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

Using nodejs, expressjs, 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 interrupt calls as below:

  1. From /mfp/api : forward these APIs as is to your MFP server url
  2. From /mfp/api/imfpush : truncate the prefix "/mfp/api" and forward the API to your MFP server url