UCCM for Web Push

Update in 2018.06.12: UCCM is not yet ready to be open to the public. An alternative to UCCM is using FCM in your site to implement Web Push.

Overview

This document is mainly for developers, introducing the Standard Web Push implementation in the UC browser, including the following:

  1. Apply for UCCM (UC Cloud Messaging) project
  2. Subscribe message push (front end)
  3. Push message (server)
  4. Best Practice

The costs of implementation:

  • Provides UCCM JS SDK for quick implementation at the front end
  • The server side only needs to manage the mapping relationship between users and subscription tokens

Apply for UCCM project

Business partners need to provide the following information:

  • business name: provide the full name of the business, and the English abbreviation
  • business owners: provide e-mail, can be more people
  • business domain: can be multiple, must support https

This step is to get a sender_id and a server_key. A sender_id is on behalf of a sender who can push messages to the subscribers. The sender_id is used for front-end SDK initialization parameters and the server_key is used for authentication when pushing messages.

Business partners can send business name, person in charge, and business domain to the mailbox uc-web-dev @ service.alibaba.com to apply a UCCM project.

register a subscription

1. service worker js

Overview: Prepare the registration script, used to register service worker.

Created a new file named messaging-sw.js, and place it in the root of your website: /messaging-sw.js.

The template is as follows:

// load JS SDK
importScripts('https://img.ucweb.com/s/uae/g/0n/uccm/1.0.3/index.js');
const messaging = uccm.messaging({
    messagingSenderId: "your_sender_id",
	unit: "intl"
});
// 3. when recieved only data payload (notofication null)
messaging.setBackgroundMessageHandler((payload, event) => {
  // Call event.stopImmediatePropagation() 
  // to  avoid "This site has been updated in the background." 
  // in the case of `condition of null == payload.notification`
  event.stopImmediatePropagation();
});

2. Initialize JS SDK

Overview: initialize JS SDK and get messaging instance.

2.1 load JS SDK

<script src="https://img.ucweb.com/s/uae/g/0n/uccm/1.0.1/index.js"></script>

2.2 When the JS SDK loaded, You get the window.uccm object, pass messagingSenderId as an parameter to uccm.messaging() to get the messaging instance

var messaging = uccm.messaging({
  messagingSenderId: "your_sender_id"
});

3. Request permission for push

messaging.requestPermission().then(function() {
  // user agreed
}).catch(function(error) {
  // user rejected
  console.log(':^(', error);
});

4. Get the registration token

messaging.requestPermission().then(function() {
  messaging.getToken()
    .then(function(currentToken) {
	  // report the token to your server along with othe business data, such as user-agent. One token represents one subscription

    }).catch(function(err) {
      console.log(':^(', err);
    });
}).catch(function(error) {
  console.log(':^(', error);
});

5. Summary

<script>
  (function () {
    // Detect if user-agent meets the requirements 
    var isHttps = location.protocol === "https:";
    var webPushSupported = (
      "serviceWorker" in navigator &&
      "PushManager" in window &&
      "Notification" in window &&
      "fetch" in window &&
      ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification") &&
      PushSubscription.prototype.hasOwnProperty("getKey")
    );
	
	// If not, return and do nothin
    if(!isHttps || !webPushSupported){
      return;
    }
	
	// util for script async loading
    var importScript = (function (oHead) {
      function loadError(oError) {
        throw new URIError("The script " + oError.target.src + " is not accessible.");
      }
      return function (sSrc, fOnload) {
        var node = document.createElement("script");
        node.async = true;
        oHead.appendChild(node);
        node.src = sSrc;
        node.onerror = loadError;
        if (typeof fOnload === "function") { node.onload = fOnload; }
      }
    })(document.head || document.getElementsByTagName("head")[0]);
	
	// If yes, the load JS SDK async
    importScript("https://img.ucweb.com/s/uae/g/0n/uccm/1.0.1/index.js", function (){
      // First, get an messaging instance
      var messaging = uccm.messaging({
        messagingSenderId: "your_sender_id",
		unit: "intl"
      });
      // then request permission
      messaging.requestPermission().then(function () {
        messaging.getToken()
          .then(function (currentToken) {
            // Send subscription token to your server
          }).catch(function (err) {
            console.log(':^(', err);
          });
      }).catch(function (error) {
        console.log(':^(', error);
      });
	  
      /* 
	    * on message listener:
        * 1. The data message is sent as a broadcast to the page
        * 2. If there is a page in the foreground, the page will receive a 
        *    broadcast message, otherwise the message will be prompted by default
        *    when push a notification
        */
      messaging.onMessage(function(payload) {
        // code something here
      });
	  
      // callback fired if token once updated.
      messaging.onTokenRefresh(function () {
        messaging.getToken()
          .then(function (refreshedToken) {
            // update subscription token
          })
          .catch(function (err) {
            console.log('Unable to retrieve refreshed token ', err);
          });
      });
    });
  })();
</script>

Code demo:

  • page: https://uccm-intl.ucweb.com/uccm/demo/10003.html
  • sw.js: https://uccm-intl.ucweb.com/messaging-sw.js

Push a message

message type

  • notification: JSON format with constraints
  • data: JSON format

data structure of a notification

{
  "title": string,
  "body": string,
  "click_action": string,
  "icon": string
}

Message pushing demo

Push notification-only payload

curl 'https://uccm.ucweb.com/uccm/send' \
-H 'Authorization: key=${your_server_key}' \
-H "Content-type: application/json" \
-d '{ "to": "iuBvoobOXOGpTN0akLcdV1NHPsuHm4rDOkF4nqAqhNQ","notification": {"title":"Rock PWAs","body": "Welcome!","click_action": "https://pwa.rocks","icon":"https://ae01.alicdn.com/kf/HTB11xzZPFXXXXaTXXXX760XFXXXu.png"}}'

Push data-only payload

curl 'https://uccm.ucweb.com/uccm/send' \
-H 'Authorization: key=${your_server_key}' \
-H "Content-type: application/json" \
-d '{ "to": "iuBvoobOXOGpTN0akLcdV1NHPsuHm4rDOkF4nqAqhNQ","data": {"name":"Rock PWAs", "action":"do something"}}'

Push the payload containing notification & data

curl 'https://uccm.ucweb.com/uccm/send' \
-H 'Authorization: key=${your_server_key}' \
-H "Content-type: application/json" \
-d '{ "to": "iuBvoobOXOGpTN0akLcdV1NHPsuHm4rDOkF4nqAqhNQ","notification": {"title":"Rock PWAs","body": "Welcome!","click_action": "https://pwa.rocks","icon":"https://ae01.alicdn.com/kf/HTB11xzZPFXXXXaTXXXX760XFXXXu.png"},"data": {"name":"Rock PWAs", "action":"do something"}}'

Indicators that matters

  • Subscription Conversion Rate = Agree PV / Banner PV
  • Message arrival rate
  • Message click rate
  • Whether active users rate is rising
  • Site conversion rate

Best Practice