Web Push SDK Integration

Introduction

Web push notifications are messages sent to a particular browser instance. Our implementation is based on the Push API which is a standard protocol being developed by the W3C and implemented in most modern browsers, including Chrome and Firefox on both traditional desktop and mobile devices.

Web push notifications can be used to keep your users informed of changes, and are especially useful given the 1-to-1 communication offered by each individual browser having their own uniquely generated ‘address’ to which messages are pushed.

The standard allows for much the same content as a mobile notification: that is a header, message, icon and optionally a large image attachment. Although, each browser implementation may present those in a different way - see below for some examples.

example notifications
browser platform example
Chrome desktop https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_380/v1487933410/web_push/chrome_message_desktop.png
Chrome desktop https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_380/v1493217624/docs_site/chrome_desktop_image.png
Chrome mobile https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_380/v1487935888/web_push/chrome_message_mobile.png
Chrome mobile https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_380/v1493217947/docs_site/chrome_mobile_image.png
Firefox desktop https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_380/v14879358/web_push/firefox_message_desktop.png

Note the large image attachment cropping on Chrome mobile. This will depend on the screen size and aspect ratio of the handset, so make sure you are aware of this when selecting images for any campaigns.

Supported Platforms

supported platforms
browser android desktop from version
Chrome yes yes 55.0
Firefox no yes 52.0
Edge no no n/a
Safari no no n/a

Integrating Into Your Website

Prerequisites

  • Your site must be fully SSL compliant, this means also forwarding users to the encrypted version of your website if they try to use an http domain, and not including any unsecure elements in page content. It is an industry best practice, as well as a lot safer for your users, to always use https and we would strongly recommend that you always use a secure origin. Due to the potentially sensitive nature of notifications, this helps prevent man-in-the-middle attacks and with modern CAs like LetsEncrpyt offering free certificates there really is no excuse not to have https everywhere.
  • You must include a manifest.json file in the root level of your site. This file should include the Sender ID from your FCM web app project. Check the Cloud Messaging tab of your FCM project settings page to locate your Sever Key and Sender ID.) Many Progressive Web Apps will have this file already, if so you should add the following field to your existing manifest.json
{
  "gcm_sender_id": "YOUR_FCM_SENDER_ID"
}
  • You will need to host a copy of our service worker and SDK in the root directory of your site. This is required by the Push API spec although you should always load the latest SDK versions from our CDN for actual usage whenever you update your site. If using a tag manager solution the integration steps may vary.

You can obtain the latest version of our SDK and Service Worker scripts from here:

https://cdn-js.360dialog.io/d360-web/1.x/d360-sw.js
https://cdn-js.360dialog.io/d360-web/1.x/d360-sdk.js

Before You Start

We will need to whitelist your domains before we can accept traffic, so make sure to speak to our integrations team during the process so that your staging and production domains can be added to the list. You will receive 403 errors if your domain has not been added the whitelist.

Direct Integration

If you are integrating our SDK directly on your web page you must add a line to load our service worker script into the <head> section of your website.

<script type="text/javascript" src="https://YOURDOMAIN.com/d360.sdk.js" async></script>

Note

Do not forget the async flag when calling for our SDK, this is a web best practice and prevents your page rendering from being blocked if the SDK takes a long time or fails to load for any reason.

Using the SDK

Initialisation Options

You can set a number of options at start by using our D360Config class. This includes setting your Xray platform app id and API Key which you can get from either our API or by using our UI client.

For authenticated users you can also send us an internal identifier which will be included with each event recorded by our SDK. This will be made available to you in reporting if you need it, or need to id match users across systems.

<script type="text/javascript">
    var D360 = [];
    var D360Options = {
        requestPushOnLoad: false,
        disableTrackingWithoutSubscription: false,
        requireInteraction: true,
        appId: 'YOUR_APP_ID',
        userId: 'KNOWN_USER_ID'
        apiSecret: 'YOUR_360DIALOG_API_KEY',
    }
</script>

Note

To avoid a race condition it is strongly suggested to put this section before loading the SDK.

If you start the SDK with disableTrackingWithoutSubscription set to true, the SDK will disregard any events sent before the user accepts push notifications. These events will not be queued. See below for more information on disabling tracking.

The requireInteraction option will force any message received with this flag not specifically set to require user interaction before is will disappear. This setting only has an impact on desktop browsers. If set to false or omitted messages received on windows, linux and mac desktop computers will automatically disappear from the screen after around 20 seconds. When this happens the message will still be available in the user’s notification shade. We strongly advise using this option with care as it could fast become annoying to users, especially for apps sending many notifications.

See the section below regarding the requestPushOnLoad setting.

Adding a Callback on Initialisation

Events sent before the SDK is ready should be queued and sent after it is initialised. However, there may be some cases, especially in very heavy pages, where it is better to wait until the SDK has fully initialised before executing any functions.

To add a callback include the following in your options block:

D360.push(['onInit', function() {
      myFunction();
  }]);

where myFunction would be your function, for example to log a message to the console you would use console.log("I'm Ready");.

Checking the state of the SDK with the onReady Callback

If you want to ensure that the SDK is ready before sending any events or calling any functions you can use the onReady function to execute another function only when the SDK is ready. This way you can fire a callback to your own app or log a message to the console.

In the below example the SDK would trigger an alert message if it is active.

D360.push(['onReady', function() {
  alert("360SDK is open for business")
}]);

If called before the SDK is ready, the function will be called on initialisation.

Registering Users for Push

Users need to opt-in to receive push messages from your through their browsers. You have the option of either asking for permission as soon as the service worker is initialised or of triggering this prompt at some later point during the session.

All users must register using the browser’s native prompt, this is in place to help users avoid spamming and ‘drive-by’ user registrations. There must always be a user action to initiate their subscription to your messages.

https://res.cloudinary.com/djr8qmdci/image/upload/c_scale,w_250/v1493741604/native-prompt-mobile-firefox_pmd5f2.png

autoregister

While we do not recommend this as it seems a bit pushy, you can set the SDK to request permission to send notifications as soon as it is started on your page.

To trigger the prompt instantly you should set the option requestPushOnLoad to true in your D360Config. Please note however, that if a user clicks ‘no’ at this time instead of simply closing the dialog, you will not be able to ask for permission again unless the user deletes this preference in their browser.

triggering the prompt on demand

A so-called ‘soft-prompt’ is when you first try to convince your website visitor or user of the benefits of opting in to push with either a message on the page or in the form of a modal or pop-up. This goes a long way to helping users understand whether this is a valuable service to them and this, in conjunction with only asking for push permission once users are authenticated (or at least known to your system), greatly increases the chances of a user agreeing to be contacted in this way.

You can set a button to trigger the opt-in using the following function:

D360.push(["requestPushNotification"]);

Providing a User ID

If you are running campaigns across different channels or exporting data into a another system, it is a good idea to provide some kind of internal identifier with which you can later use to identify events created by the same users across, for example, mobile and web, or across different web browsers.

Use the updateExternalData method to set a userId

D360.push('updateExternalData', {userId: 12345});

or, if this is already known when initialising the SDK, you can set the value of userId by providing this in the D360Options object.

The user id will be added to each event sent to our backend and made available in our reporting database.

Unregistering Users

While the Push API comes with built-in controls for users to manage their notification preferences, it is always a best practice to present this option to the user themselves. After all, choice is something that we all crave, and giving the user the choice to opt-out directly with you rather than through their browser means the choice to opt back in can be made much easier, and with a much fuller sense that this is what they really want.

To unregister a user create a button that executes the following java function on click:

D360.push(["unregister"]);

The service worker will stay registered after a user unsubscribes using this method and will not be terminated, but it will not display messages to users even if they are received.

You can re-register users again using the requestPushNotification method as before. The benefit of offering a soft opt-out route is also clear at this step as the user re-registers with a single click and we avoid the need to trigger the browser’s native prompt a second time, removing a point of failure and friction in the opt-in flow.

However, there might be cases where you need to give users an option to completely wipe their subscription. This is a complex process of stopping and unregistering service workers, as well as removing cookies relating to the push subscription. For most users it is beyond the limits of what they are willing to do themselves and, indeed, in some jurisdictions it is a legal requirement that users be given this power over their own data and lines of communication.

If a user wants to go beyond simply unregistering but wants to sever the connection to their browser and stop all functioning you can provide a way for them to trigger the D360.push(['wipeDeviceData']) function. This will unregister the service worker and clear our cookie from local storage for this user agent. You will get some messages to let you know the outcome of the operation including whether the service worker was successfully unregistered and how much data was cleared so you can log these to the console and display an additional confirmation to the user if no errors were received. You will need to also force reloading of the browser window so that it can re-initialise without the service worker. It is critically important that if you have not opted to use a soft-prompt, that you do not trigger the automatic permission prompt when the page reloads as this will only annoy the user.

Disabling Tracking

You can disable event tracking in the SDK by using the disableEventTracking method and setting this to either true or false. This setting will not be persisted so it is important to call this each time the SDK loads for users who have expressed a preference to opt out of tracking. Please not that certain system events may still be sent.

Example:

D360.push(['setEventTrackingDisabled',false]);

Tracking can also be disabled for any user who has not opted in to push by including disableTrackingWithoutSubscription: true, in the D360Options object.

You’re All Set!

Head over to our API or UI documentation for help on setting up your first test campaigns. Remember, before you can register users and start sending messages, you will need to make sure your domain has been whitelisted as per the prerequisites section.