dotdigital Engagement Cloud

The dotdigital Engagement Cloud developer hub

Official dotdigital Engagement Cloud APIs documentation

Using the JavaScript SDK with cross-platform apps

A tutorial for adding the JavaScript SDK code to your app to allow your app users to receive push notifications from your Engagement Cloud account.

Unlike our native mobile SDKs, the JavaScript SDK is for cross-platform apps, therefore, after you've added the JavaScript SDK code to your app, you must use a framework, such as Cordova (with PhoneGap) to get a native device token (registration ID), and send it to Engagement Cloud through the JavaScript SDK.

JS framework sending the registration ID between Engagement Cloud and your app

JS framework sending the registration ID between Engagement Cloud and your app

To set up push notifications for cross-platform apps, complete the following tasks:

  1. Install the JavaScript SDK
  2. Configure the JavaScript SDK
  3. Initialise the JavaScript SDK
  4. Register the push tokens for the app

Sample Code

This tutorial explains how to use the SDK with JavaScript, but you can find a full sample of the TypeScript code in the 'JavaScript SDK sample code in TypeScript' section.

More sample apps including Cordova implementations can be found here, the Foundation SDK samples are the samples to look at:

Installing the JavaScript SDK

The JavaScript SDK can be installed from either NPM or Bower, depending on your intended usage.

ES6 Promises

ES6 Promises are used in this SDK which are widely supported in web containers and browsers, but depending on which browsers you are targeting, you may need to use a polyfill such as: es6-shim

Classical JavaScipt

If you use classical JavaScript in your project, and you just want to include a script that exposes some global objects on your page, use Bower.

Bower

  1. Install the JavaScript SDK
$ bower install comapi-sdk-js-foundation
  1. Import the script into your project
<script src="bower_components/comapi-sdk-js-foundation/dist/comapi-foundation.js"></script>
//Minified version
<script src="bower_components/comapi-sdk-js-foundation/dist/comapi-foundation.min.js"></script>

ES6 JavaScript

If you use ES6 modules in your project, for example in the Angular and Ionic 2 frameworks, use NPM. The examples for the NPM package are in TypeScript because the NPM version of the SDK is written in TypeScript.

NPM

  1. Install the JavaScript SDK
$ npm install @comapi/sdk-js-foundation --save
  1. Import the Foundation, ComapiConfig, and IAuthChallengeOptions modules from the SDK file
import { Foundation } from "@comapi/sdk-js-foundation"
import { ComapiConfig } from "@comapi/sdk-js-foundation"
import { IAuthChallengeOptions } from "@comapi/sdk-js-foundation"

White listing the SDKs API calls

The built in security in Cordova based apps will restrict the URIs the Cordova app pages can access, therefore you will need to white list the URIs the SDK uses in order for it to operate. To do this do the following:

If using the cordova-plugin-whitelist

Ensure the following line is added to your config.xml file in your project:

<allow-navigation href="https://*.comapi.com/*" />

If using Content-Security-Policy tags

Ensure your Content-Security-Policy tags include the following directive:

connect-src https://api.comapi.com:*

For example:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;connect-src https://api.comapi.com:*">

Configuring the JavaScript SDK

Before you can configure the JavaScript SDK, you need the following:

var comapiConfig = new COMAPI.ComapiConfig();
  1. Pass your API Space ID to the withApiSpaceId() method
var comapiConfig = new COMAPI.ComapiConfig()
    .withApiSpace(appConfig.apiSpaceId);
  1. Pass the function that creates a JWT to the withAuthChallenge() method
var comapiConfig = new COMAPI.ComapiConfig()
    .withApiSpace(appConfig.apiSpaceId)
    .withAuthChallenge(challengeHandler);

Initialising the JavaScript SDK

After you've configured the SDK, pass the comapiConfig object to the initialise() method.

This method creates a valid session by calling your JWT function and by using the JWT to create the user's profile ID (profileId string).

When a session is stopped and started again, a new JWT token is created and used to create a new profile ID.

A session is stopped in any of the following circumstances:

  • The user uninstalls the app, and then reinstalls it
  • The user clears all of the app's data

Your app needs a valid session in order to add an email address to the user's profile.

COMAPI.Foundation.initialise(comapiConfig)
    .then(function (sdk) {
        console.log("Foundation interface created", sdk);
    })
    .catch(function (error) {
        $log.error("paragonService: failed to initialise", error);
    });

At this point, push notifications can't be displayed on the device of your app users, unless you use a third-party framework to get a native device token and handle displaying the push notification.

JavaScript SDK sample code in TypeScript

// some app specific imports
import { AppSettings } from "../settings";
import { AuthService } from "./auth";

// Comapi class / interface imports
import { Foundation, ComapiConfig, IAuthChallengeOptions } from "@comapi/sdk-js-foundation"

export class ComapiService {

    public sdk: Foundation;

    private challengeHandler(options: IAuthChallengeOptions, answerAuthenticationChallenge) {
        this._authService.getToken(options.nonce)
            .then((token) => {
                answerAuthenticationChallenge(token);
            });
    }

    constructor(private _authService: AuthService) { }

    /**
     * Public method to encapsulate up the initialisation of Comapi 
     */
    public initialise(): Promise<Foundation> {

        return new Promise((resolve, reject) => {

            if (this._authService.isAuthenticated()) {

                let comapiConfig = new ComapiConfig()
                    .withApiSpace(AppSettings.APP_SPACE_ID)
                    // Note the this pointer binding so I can access this._authService in the authChallenge calllback
                    .withAuthChallenge(this.challengeHandler.bind(this));

                Foundation.initialise(comapiConfig)
                    .then((sdk) => {
                        this.sdk = sdk;
                        console.log("foundation interface created");
                        resolve(sdk);
                    })
                    .catch((error) => {
                        console.error("initialise failed", error);
                        reject(error);
                    });
            } else {
                reject("Not logged in");
            }
        });
    }
}

Using a JavaScript framework to get a native device token

Many frameworks, such as React Native, Cordova with the PhoneGap plugin, and Ionic Capacitor, can be used to display incoming push notifications from Engagement Cloud.

This tutorial uses the Cordova framework with the PhoneGap plugin, but any framework that you choose to use must be able to get a native device token (registrationId).

If your app is for use on iOS, you'll need to have your app ID's bundle ID. This ID must match the value of the id attribute in the <widget> element of your config.xml file.

If your app is for use on Android, you'll need to have your app's package name that you entered in your push notification profile.

Getting a registration ID, using the Cordova framework with the Adobe PhoneGap plugin

Push notifications can be sent only if the registration ID (registrationId) is successfully passed to the JavaScript SDK.

Getting the registrationId is an asynchronous task that is performed after the Cordova deviceready event.

import { Push } from 'ionic-native';

platform.ready().then(() => {

    let push = Push.init({
        //For Android apps
        android: { senderID: 'Your_Project_ID' },
        //For iOS apps
        ios: {
        alert: "true",
        badge: true,
        sound: 'false'
        }
    });

    push.on('registration', (data) => {
        console.log("got a registration ID", data.registrationId);
        localStorage.setItem("registrationId", data.registrationId);
    });
  
    push.on('notification', (data) => {
          console.log("got a push notification", data);
      });
  
 		push.on('error', (error) => {
     		 console.error('Error with Push plugin', error);
		});

}
platform.ready().then(() => {

    const push = PushNotification.init({
        //For Android apps
        android: { senderID: 'Your_Project_ID' },
        //For iOS apps
        ios: {
        alert: "true",
        badge: true,
        sound: 'false'
        }
    });

    push.on('registration', (data) => {
        console.log("got a registration ID", data.registrationId);
        localStorage.setItem("registrationId", data.registrationId);
    });
  
    push.on('notification', (data) => {
          console.log("got a push notification", data);
      });
  
 		push.on('error', (error) => {
     		 console.error('Error with Push plugin', error);
		});

}

Displaying push notifications while the app is in the foreground

Push notifications are automatically displayed only while the app is in the background. These notifications are sent to the system tray (Android) or the Notification Center (iOS) and launch your app when users tap them.

If you want to display the push notification message while the app is in the foreground, do one of the following:

Android

For Android devices, you can choose to have push notifications displayed automatically when the app is in the foreground, or you can choose to display the push notification message yourself.

Displaying push notifications automatically

When you choose to have push notifications displayed automatically when the app is in the foreground, the on('notification') callback is run only when the user taps the notification. Therefore, you can decide what happens when the user taps the notification

The push notification is passed as an argument to the push.on('notification') callback.

  • On the init() method of the push plugin, set the android object's forceShow property to true (it's set to false by default).
import { Push } from 'ionic-native';

let push = Push.init({
        //For Android apps
        android: { senderID: 'Your_Project_ID',
                 	 forceShow: true
                 }
});
const push = PushNotification.init({
        //For Android apps
        android: { senderID: 'Your_Project_ID',
                 	 forceShow: true
                 }
});

Displaying push notifications yourself

If you want contol over how push notification messages are displayed, you can implement your own way of displaying the push notification while the app is in the foreground.

For this option, the on('notification') callback is run immediately, and the push notification is passed as an argument to it.

  • On the init() method of the push plugin, make sure the android object's forceShow property is set to false (it's set to false by default).

For iOS

You need to implement your own way of displaying the push notification while the app is in the foreground. The push notification is passed as an argument to the push.on('notification') callback.

Sending the registration ID to the JavaScript SDK

After you initialise the JavaScript SDK and you have a valid session, you need to send the registration ID to the JavaScript SDK.

The JavaScript SDK expects the registration ID to be passed to different methods, depending on the operating system. Therefore, use the cordova device plugin to find out which platform the user is on.

import { Environment } from "@comapi/sdk-js-foundation";

// Put this somewhere appropriate in your app (at the end of you initialisation/login flow)

let registrationId = localStorage.getItem("registrationId");
// skip if registrationId hasn't been collected
if(registrationId){

    // There are separate methods to call, depending on the operating system
    if (platform.is('ios')) {

        // You need to create an APNs certificate in the Apple Developer Portal.
        // You must upload this cerificate to your push notification profile in Engagement Cloud
        // This certificate can be of type 'development' or 'production', hence the Environment parameter
        sdk.device.setAPNSPushDetails("<Bundle Id>", Environment.development, registrationId)
        .then(result => {
            console.log("setAPNSPushDetails() succeeded", result);
        })
        .catch(error => {
            console.error("setAPNSPushDetails() failed", error);
        });

    }else if(platform.is('android')){

        sdk.device.setFCMPushDetails("<Package Name>", registrationId)
        .then(result => {
            console.log("setFCMPushDetails() succeeded", result);
        })
        .catch(error => {
            console.error("setFCMPushDetails() failed", error);
        });

    }
}else{
    console.error("no registrationId ;-(");
}

Now, when a user launches your app, the user's profile data is sent to Engagement Cloud and (if that profile contains an email address that belongs to one of your contacts) that contact can now receive push notifications from Engagement Cloud :tada+: .

Next steps

Now ensure your app passes an email address to the SDK for the app user to ensure they get a contact created in Engagement Cloud by following these instructions

Updated about an hour ago

Using the JavaScript SDK with cross-platform apps


A tutorial for adding the JavaScript SDK code to your app to allow your app users to receive push notifications from your Engagement Cloud account.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.