Integration

Kumulos provides an SDK to ease the integration of the Kumulos Analytics and Push Notification features into your web project. This guide provides an overview of setting up the SDK for your project and sample usage.

Project Setup & Initialization

The Kumulos libraries are distributed through a CDN or NPM. For both integrations, you will need your Kumulos API key and secret key which can be found on the app dashboard in Kumulos' control panel. For configuring web push, you will also need the VAPID public key from the web push configuration dialog.

Note that in order to use web push notifications, your site must be served over HTTPS.

Website/CMS Projects using CDN

Select the app, expand 'Messaging' in the left menu, click 'Configuration' and then the cog next to the web icon.

Click the copy icon to copy the code snippet (that includes your Kumulos API key, secret key and VAPID public key) and paste this into the <head> tag.

Web Push SDK Code Snippet for CDN

Next, host a service worker at https://your-domain.com/worker.js with the code snippet copied from the 'worker' tab of the web push configuration dialog:

Web Push SDK Service Worker Code Snippet

PWA/SPA Projects using NPM

Start by adding the package dependency to your project:

npm install --save @kumulos/web

After installation, import and initialize the SDK in your application code using the code snippet from the 'NPM' tab of the web push configuration dialog:

Web Push SDK Code Snippet for CDN

Next, host a service worker at https://your-domain.com/worker.js with the code snippet copied from the 'worker' tab of the web push configuration dialog:

Web Push SDK Service Worker Code Snippet

Configuring Service Worker Location

If you want to host the service worker file at a different path on your domain, you can configure the path during initialization as follows:

Kumulos('init', {
    apiKey: 'YOUR_API_KEY',
    secretKey: 'YOUR_SECRET_KEY',
    vapidPublicKey: 'YOUR_VAPID_KEY',
    serviceWorkerPath: '/wp-content/themes/your-theme/assets/sw.js'
});

Checking Integration

When you run visit your web project in a browser, you can check that the SDK has been initialized correctly by selecting the app and clicking the Installs tab to see the ten most recent installs of your project. Click on any install to see more information.

Recent installs

If you experience any difficulties integrating an SDK or initializing the Kumulos client, please don't hesitate to contact support who are standing by to help!

Installation ID

When initialized for the first time, the Kumulos SDK will create a unique identifier for the web installation that initialized the SDK.

This identifier can be used to target push notifications to a specific device through KScript or the Push Notifications API.

In order to retrieve this installation ID, simply access the method.

For website projects:

Kumulos(function (client) {
    client.getInstallId().then(function (installId) {
        // Use the install ID for something
    });
});

For PWA projects:

const installId = await kumulosClient.getInstallId();

Once you have the installation ID, you can send it to your web backend to be used later for push targeting. For more information about push targeting, please see the KScript Documentation or push notification documentation as appropriate.

Analytics

Kumulos provides concise and easy to consume analytics & reporting features. By initializing the SDK, you automatically get engagement reporting and page view events out the box.

User Association

Kumulos allows associating a user identifier with the current installation ID. This user identifier is useful for performing analytics aggregations & analyses at the user level, for example, funnels completed by users across multiple devices. You can also optionally associate a collection of attributes with the user.

To associate the current app installation with a user, you can use the helper method as shown below.

For website projects:

Kumulos('associateUser', 'unique-user-id');

For PWA projects:

kumulosClient.associateUser('unique-user-id');

User association is time-aware, so say two different users log in to the app, their user IDs will be associated with the same install for the time between subsequent calls to the helper method. For example:

Kumulos('associateUser', 'Bob');
// This event will belong to Bob
Kumulos('trackEvent', 'product.purchased');
Kumulos('associateUser', 'Alice');
// This event will belong to Alice
Kumulos('trackEvent', 'product.purchased');

Attributes

You can optionally associate a collection of attributes with the user for targeting, personalization or attribution. To associate attributes with the user, pass a collection into the helper method as shown.

Kumulos('associateUser', 'unique-user-id', {
    name: 'Shawn',
    age: 25
});

If you do not have a user identifier, use the installation ID generated by the Kumulos SDK.

Event Tracking

Kumulos allows you to track custom analytics events that can be used as a trigger to fire automation rules (e.g. to trigger a push notification) or as steps in a funnel to track conversion through key user journeys in your project.

Track conversion

To track a custom analytics event, use the trackEvent method.

For website projects:

Kumulos('trackEvent', 'product.purchased', {
    productId: 404
});

For PWA projects:

kumulosClient.trackEvent('product.purchased', {
    productId: 404
});

Checking Events from your Project

When you test your project, you can check that the SDK is recording events correctly by selecting the app and clicking the Installs tab to see the ten most recent installs of your project. Click on any install and then click on the Events tab.

Install events

Alternatively, to see counts of all analytics events, including system events such as opened a push notification, recorded by installs of the app in the last 30 days, expand 'Analytics' and click 'Explore' in the left menu.

Analytics Explorer

Page View Events

For website projects, the Kumulos SDK automatically gathers page view events which include the following properties:

  • page title (e.g. Checkout)
  • path (e.g. /blogs/super-cool-announcement)
  • query parameters (e.g. utm=your_campaign)

For PWA projects, you can track page view events as follows by hooking into your SPA router. For example (using the history module):

import { createBrowserHistory } from 'history';
import Kumulos from '@kumulos/web';

const kumulosClient = new Kumulos({...});
const history = createHistory();

history.listen(location => {
    let query = undefined;
    const qs = location.search;

    if (qs.length > 0) {
        query = qs
            .substring(1)
            .split('&')
            .map(vars => vars.split('='))
            .map(pairs => pairs.map(decodeURIComponent))
            .reduce((q, pair) => ({ ...q, [pair[0]]: pair[1] }), {});
    }

    kumulosClient.trackEvent('k.pageViewed', {
        title: 'your page title',
        path: location.pathname,
        query
    });
});

Messaging & Push Notifications

Kumulos provides powerful multi-channel messaging services to reach your users. By initializing the SDK you can quickly and easily receive push notifications to re-engage your users and keep them up to date.

Configuration & Setup

To integrate into your web project, you have to complete the following steps:

  1. Enable Push in the Kumulos Agency Console
  2. Integrate the SDK components with your web project
  3. Register to receive push notifications from your website or PWA

Registering for Web Push Notifications

In order to send push notifications to your users, you have to request permission to send them notifications. This section outlines how to request permission using the Kumulos Soft Prompts (recommended), or requesting permission directly from a widget of your choosing.

Using Soft Prompts

The soft prompt mechanism offers the user a method to indicate intent to opt in to notifications prior to being asked for the native browser permission. Soft prompts follow best-practices for user experience and will stay up to date with current browser requirements.

You can configure the soft prompts in the SDK with the pushPrompts option during initialization, passing either 'auto' (default), or an object describing the prompts.

In the case of 'auto', the prompt configuration will be managed from the Kumulos Console's push configuration page.

Alternatively, you can specify the prompts in the code directly:

Kumulos('init', {
    apiKey: 'YOUR_API_KEY',
    secretKey: 'YOUR_SECRET_KEY',
    vapidPublicKey: 'YOUR_VAPID_KEY',
    pushPrompts: {
        'my-bell-prompt': {
            type: 'bell',
            trigger: {
                event: 'k.pageViewed',
                afterSeconds: 3,
                filters: [
                    ['path', 'in', ['/', '/blog/*']],
                ]
            },
            labels: {
                tooltip: {
                    subscribe: 'Get the latest updates!'
                }
            },
            colors: {
                bell: {
                    bg: '#fa0',
                    fg: '#fff'
                }
            },
            position: 'bottom-left'
        }
    }
});

The above example defines a bell prompt which will show to the user on the home and blog pages, after three seconds of being on the page.

Prompt configuration follows the following interfaces:

type FilterOperator = 'in';
type FilterValue = number | boolean | string | string[];
type PropFilter = [string,FilterOperator,FilterValue];

interface PromptTrigger {
    event: string;
    afterSeconds?: number;
    filters?: PropFilter[];
}

interface BellPromptConfig {
    type: 'bell';
    trigger: PromptTrigger;
    labels?: {
        tooltip?: {
            subscribe?: string;
        };
    };
    colors?: {
        bell?: {
            bg?: string;
            fg?: string;
        };
    };
    position: 'bottom-left' | 'bottom-right';
}

Request Directly

To prompt your user for permission, you can use the pushRegister method. This will ask the user to accept notifications, and then subscribe them if they accept.

It is recommended to prompt the user as a result of interaction on the page. Once a user blocks notifications, you cannot prompt them again using the browser's dialog so it's a good idea to ask them if they'd like update before calling the pushRegister method.

Future browser updates will likely make this mandatory for many browsers

In a website project:

Kumulos('pushRegister');

For a PWA project:

kumulosClient.pushRegister();

Advanced

Checking Integration Status

When you test your project, you can check that the integration has been successful using the install browser by selecting the app in the Kumulos Console and clicking the Installs tab to see the ten most recent installs of your project.

Click on an install, click the 'Push' tab and click Send Test Push.

Install push details

If you do not receive the push notification, check the Error Log for any errors sending the push notification to the native push gateways. If you continue to experience problems, please don't hesitate to contact support who are standing by to help!

Handling Notification Events

The Kumulos SDK exposes two optional handlers for notification events. These handlers can be used to perform actions on your page in response to notification data and content.

To configure the handlers, pass functions to the initialization options:

new Kumulos({
    // ... other options
    onPushReceived: function (n) {
        console.log('Received: ', n);
    },
    onPushOpened: function (n) {
        console.log('Opened: ', n);
    }
});

Both handlers are optional.

onPushReceived will be triggered on all currently open tabs when any push notification is received from Kumulos.

onPushOpened will be triggered on the newly-opened tab after Kumulos has been initialized. Any other open tabs will not receive the open callback.

Note Safari is not supported due to lack of W3C push implementation.

Both handlers receive a notification object as their only argument, it has the following interface:

interface KumulosPushNotification {
    id: number;
    title: string;
    message: string;
    url?: string;
    iconUrl?: string;
    imageUrl?: string;
    data: {
        [key: string]: any;
    };
}

Channels

You can create and manage subscriptions to channels from the SDK. Channels allow you to send messaging content to certain interest groups.

All channel management is performed with an instance of the ChannelSubscriptionManager. The manager is available from an SDK client instance as follows.

For website projects:

Kumulos(function (kumulosClient) {
    var subscriptionManager = kumulosClient.getChannelSubscriptionManager();
});

For PWA projects:

const subscriptionManager = kumulosClient.getChannelSubscriptionManager();

All further examples will reference the subscription manager, which exposes the following interface:

interface Channel {
    uuid: string;
    name?: string;
    subscribed: Boolean;
    meta?: PropsObject | null;
}
interface ChannelSpec {
    uuid: string;
    subscribe: boolean;
    meta?: PropsObject | null;
    name?: string;
    showInPortal?: boolean;
}
interface ChannelSubscriptionManager {
    /**
     * Subscribes to the channels given by unique ID
     */
    subscribe(uuids: string[]): Promise<Response>;
    /**
     * Unsubscribes from the channels given by unique ID
     */
    unsubscribe(uuids: string[]): Promise<Response>;
    /**
     * Sets the current installations channel subscriptions to those given by unique ID.
     *
     * Any other subscriptions will be removed.
     */
    setSubscriptions(uuids: string[]): Promise<Response>;
    /**
     * Clears all of the existing installation's channel subscriptions
     */
    clearSubscriptions(): Promise<Response>;
    /**
     * Lists the channels available to this installation along with subscription status
     */
    listChannels(): Promise<Channel[]>;
    /**
     * Creates a push channel and optionally subscribes the current installation.
     *
     * Name is optional, but required if showInPortal is true.
     */
    createChannel(channelSpec: ChannelSpec): Promise<Channel>;
}

Channel visibility and metadata

Channel visibility and meta data can be controlled when they are created.

Browser Feature Support

The following table illustrates which web push features are supported by different browsers on different operating systems.

Web Push Browser Feature Support

Changelog

1.5.0

  • Add notification event handlers for notification received and opened

1.4.0

  • Safari push notifications support
  • Allow subscribing to a channel from a soft prompt

1.3.1

  • Fix soft prompt heading color

1.3.0

  • Add configurable, optional interstitial page overlay shown when requesting native push permission

1.2.3

  • Fix base64 URL variant encoding

1.2.2

  • Render prompt UI using a portal

1.2.1

  • Reduce cache time for prompt config to one hour

1.2.0

  • Add auto resubscribe feature for migrating push subscriptions to Kumulos on next site visit
  • Implement all filter operators for soft prompt triggers

1.1.0

  • Add a configurable 'bell' soft prompt for push notifications
  • Show push notifications until the user dismisses them

1.0.1

  • Fix bug handling URL opening

1.0.0

  • Initial release with support for web push notifications and analytics events