Skip to content

W3C Push Notifications

Mobile Services supports sending push notifications to Google Chrome, Mozilla Firefox, and Microsoft Edge browsers using the W3C Push API. For the browser support matrix, see developer.mozilla.org: Using the Notification API. Once registered, the browser will receive notifications from Mobile Services, even if the user is not on your web page.

Architecture

SAP Mobile Services provides you nearly a turn key solution to add W3C Push Notifications to your existing web site. This diagram illustrates the suggested set-up:

W3C Push Diagram

A mobile application is defined in the SAP Mobile Services. This uses the mobile connectivity and notifications features. The connectivity feature defines a mobile destination to your web application server. The web application includes the JavaScript code that is needed to register and unsubscribe from push.

The desktop browser connects to your web application via the connectivity destination. This requires authorization through the IDP and the user is identified.

Required Steps

  1. Add the Mobile Push Notification feature to a mobile application definition in the cloud cockpit
  2. Enable W3C push in the feature configuration
  3. Add JavaScript code to your web site to support W3C push notification
    1. Register for push at mobile services
    2. (Optional) Stop browser push notification and unsubscribe from push in mobile services.
  4. Add the Mobile Connectivity feature to a mobile application definition in the cloud cockpit
  5. Define a destination, pointing to your web application server. Use the default values.
  6. Copy the Destination URL from the APIs tab and add /?auth=uaa to this URL. Open this URL in a browser.
  7. Authenticate and register for push in your web application.
  8. Generate a push notification.
    1. See Sending Notifications via the REST API or
    2. Navigate to the Mobile Notification feature and Push Registration tab. Select the registered user and press on Send Notification

Web Application Code

This documentation will not cover all aspects of the Push API but will focus on the steps specific to Mobile Services. Especially the concept of Service Workers and the actual subscription call is left out. Excellent documentation covering all aspects of the complete process is available developer.mozilla.org: Push API.

You need a device ID and store it locally, see: developer.mozilla.org: localStore. The device ID is used by Mobile Services to identify the caller when removing the push registration.

CORS The code needs to run from a HTTPS connection and the path /mobileservices needs to be proxied to the mobile services server URL, see Required Steps.

Create Push Registration and Register for Push

The client code needs to get the server push ID for subscribing to push:

Example: How to get the push ID:

    function getServerKey() {
        /* read PushID from mobile application */
        fetch('/mobileservices/push/v1/runtime/applications/dummy/pushconfigurations/os/w3cpushapi/pushid', {
            method: 'GET',
            cache: 'no-cache',
        }).then((response) => {
            if (response.status >= 400 && response.status < 500) {
                return response.text()
                    .then((responseText) => {
                        console.log('Failed web push response: ', response, response.status);
                    });
            }
            else {
                response.json().then((pushid) => {
                    return pushid.pushId;
                });
            }
        });
    }

Now the client code can subscribe using the W3C Push API. Finally the client code registers for push at mobile services or update an existing registration.

    function register() {
        /* try to read deviceID from store */
        var deviceId = localStorage.getItem("mobile-device-id");
        if (!deviceId) {
            /* No device ID found - create one */
            /* you may use a better solution, like a generated UUID */
            deviceId = Math.floor(Math.random() * 1000000000).toString();
            localStorage.setItem("mobile-device-id", deviceId)
        }
        var body = {
            'pushToken': subscription,
            'formFactor': 'browser'
        };

        /* try to register the browser - if there is a conflict we will update the existing record */
        fetch('/mobileservices/push/v1/runtime/applications/any/os/w3cpushapi/devices/' + deviceId, {
            method: 'POST',
            cache: 'no-cache',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ pushToken: JSON.stringify(body) })
        }).then((response) => {
            if (response.status == 409) {
                fetch('/mobileservices/push/v1/runtime/applications/any/os/w3cpushapi/devices/' + deviceId, {
                    method: 'PUT',
                    cache: 'no-cache',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ pushToken: JSON.stringify(body) })
                }).then((response) => {
                    console.log('Push registration update response: ', response, response.status);
                });
            } else {
                console.log('Push registration response: ', response, response.status);
            }
        });
    }

Unsubscribe From Push

Please provide an unsubscribe action to your web application, ensuring that the registration is removed from the mobile notifications too. You can achieve this by the following code snippet:

    function onDeleteRegister() {
        var deviceId = localStorage.getItem("mobile-device-id");
        // Remove the subscription from Mobile Services
        fetch('/mobileservices/push/v1/runtime/applications/any/os/w3cpushapi/devices/' + deviceId, {
            method: 'DELETE',
            cache: 'no-cache'
        }).then((response) => {
            console.log('Push registration delete response: ', response, response.status);
        });
    }

Last update: August 17, 2020