This guide shows you how to send web pop-ups and push notifications.

If you have not already completed the Web Quick Start Guide, complete that first before following this guide. The quick start guide shows you how to setup CleverTap’s JavaScript library on your website, track events, create user profiles, and engage users by showing them a notification.

Web Pop-Ups

A CleverTap web pop-up is a modal alert-type message view displayed by CleverTap in your desktop or mobile website.

CleverTap web pop-ups come in two types:

  • Simple Web Pop-up Notifications. You can use these templates to create your notifications including a box notification, a banner notification, and interstitial notification.
  • Exit Intent Notifications. These are displayed just before the user exits your site. These are available for desktop only.

User clicks on a web notification can be silent, open a url or invoke a javascript function. Custom key value pairs can also be passed to the invoked javascript function. You may also include a pre-set or custom image to be displayed in the notification.

Click Tracking

Currently, we don’t support tracking clicks on custom web pop-ups.

Adding Close buttons to web pop-ups

You can add a close button to your web pop-up.

Box

<div class="btn">CLOSE</div>
<script>
var btn = document.querySelector('.btn');
var wrapper = window.parent.document.getElementById('wizParDiv0');
btn.addEventListener('click', closePopUp);
function closePopUp()
{ wrapper.remove(); }
</script>

Banner

<div class="btn">CLOSE</div>
<script>
var btn = document.querySelector('.btn');
var wrapper = window.parent.document.getElementById('wizParDiv2');
btn.addEventListener('click', closePopUp);
function closePopUp() { wrapper.remove(); }
</script>

Interstitial

<div class="btn">CLOSE</div>
<script>
var btn = document.querySelector('.btn');
var overlay = window.parent.document.getElementById('intentOpacityDiv');
var wrapper = window.parent.document.getElementById('intentPreview');
btn.addEventListener('click', closePopUp);
function closePopUp()
{ overlay.remove(); wrapper.remove(); }
</script> 

Defining a Custom Rendering Listener

Using this custom callback, you will be able to control the look, feel and location of the web pop-up which you create in your CleverTap Dashboard.

You need to explicitly call clevertap.raiseNotificationViewed(); & clevertap.raiseNotificationClicked(); to ensure that notification views and clicks are tracked in your CleverTap Dashboard.

To define the callback and raise the clicked and viewed events, you need to add the following snippet to the embed code.

clevertap.notificationCallback = function(msg){
      //raise the notification viewed and clicked events in the callback
      clevertap.raiseNotificationViewed();
      console.log(JSON.stringify(msg));//your custom rendering implementation here
      var $button = jQuery("<button></button>");//element on whose click you want to raise the notification clicked event
      $button.click(function(){
         clevertap.raiseNotificationClicked();
      });
};

The msg will be in the format below. msgId contains the campaign id and the date stamp so you can programmatically decide whether to show the notification or not. kv contains the custom key value pairs.

{
    "msgContent": {
        "title": "hello title!",
        "description": “hello message!"
    },
    "msgId": "1439796272_20160219",
    "kv": {
        "key1":"value1",
        "key2":"value2"
    }
}

Web Push

Web push notifications are currently supported for Chrome version 50 for Desktop and Android and work only on HTTPS sites.

Chrome Web Push

Add the CleverTap JavaScript Library

Integrate the CleverTap JavaScript library by following the Web Quick Start Guide.

Integrate FCM and CleverTap

FCM has deprecated its existing web push protocol post-July, 2019, and moved to the VAPID protocol.

If your server key and sender ID were generated before July 2019, the legacy protocol will continue to work. However, if they were generated after July 2019, only the VAPID protocol will be supported.

We recommend that you use VAPID protocol due to increased security.

Legacy protocol steps:

Get your Sender ID and Server Key. In the CleverTap Dashboard, go to Settings → Integrate Web Push and add your Server Key.

VAPID protocol steps:

Get your Public and Private key pair from Firebase. In the Firebase console, go to your Project > Project Settings > Cloud Messaging > Web Configuration > Generate Key Pair

In the CleverTap Dashboard, go to Settings > Integrate Web Push > Select use VAPID Spec and add the generated Public and Private Key Pair.

Re-subscription of users

After you move from legacy to the VAPID protocol, we recommend that you re-subscribe the users with legacy tokens to move them to VAPID. In this case, the permission pop-up will not re-appear. The subscription will happen in the browser's background silently.

However, to help you in the migration process, we will also support the legacy protocol simultaneously even though VAPID is enabled. This will ensure web push delivery across all your subscribed users.

Firefox Web Push

Note

Currently, we do not support web push on mobile devices.

Add the CleverTap JavaScript Library

Integrate the CleverTap JavaScript library by following the Web Quickstart Guide.

Generate VAPID keys

The VAPID keys can be generated using following methods:-

  1. Using npm package name web-push (recommended)
  2. You can also use VAPID keys generated for Chrome web push in FCM account as described here. Same VAPID keys will be valid for Chrome as well as Firefox web push.

Paste VAPID keys in CleverTap

In the CleverTap Dashboard, go to Settings > Integration > Web Push > add the generated VAPID public and Private Key Pair under Firefox Web Push section

Add the Service Worker File

This section is applicable for Chrome and Firefox browsers. Push notifications on browser use a special script called a service worker that listens for web pushes. Since the execution of these scripts is managed by the browser in the background, users can receive push notifications from your website even when they’re not on your site. To get started, download the service worker file we have provided and copy it in your document root of your website, such that it’s publicly accessible.

Download the service worker file from here. As mentioned above, you’ll have to host this file in your document root.

Integration with Existing Service Worker File

Import CleverTap's service worker at the start of your existing service worker. Add the following code snippet :

importScripts('https://s3-eu-west-1.amazonaws.com/static.wizrocket.com/js/sw_webpush.js');// remove CleverTap server worker from your root folder

Specify the Sender ID in manifest.json File

This section is applicable for Chrome and Firefox browsers.

Note

This step is required only if you are using the legacy protocol.

In order to register the service worker and subscribe for push notifications, you need to specify your Sender ID inside a website manifest file.

If your website already has a manifest, simply add the following property to it. Your Sender ID is your FCM Project Number (12 digit number) and not your API Key.

{
  "gcm_sender_id": "YOUR_SENDER_ID"
}

If you don’t have a manifest file yet, create a new file called manifest.json and add it in the document root of your website. Ensure that you specify the "name" and "gcm_sender_id" parameters, where "name" is the name of your brand (e.g. “Acme Fashion”).

Here is a sample manifest.json file.

{
  "name": "Acme Fashion | Latest in fashion world",
  "gcm_sender_id": "1234567890" // replace with actual value
}

Then, in all your HTML files, include the below snippet in the header.

<head>
  <link rel="manifest" href="/manifest.json">
</head>

Safari Web Push

Note

Currently, we do not support web push on mobile devices.

Dashboard setting

Enable safari push from the CleverTap dashboard and provide the required credentials.

On the CleverTap dashboard, click Settings > Engage > Channels > Web push.

Toggle the Safari Web Push button and provide the credentials.

Set Safari

To setup a Safari Web push certificate, follow the steps below:

In OS X v10.9 and later, you can dispatch Safari Push Notifications from your Web server to OS X users by using the Apple Push Notification service (APNs). This is different from local notifications because push notifications can reach your users even if your Website or Safari browser is not open.

To integrate push notifications on your Website, you must first present an interface that allows the user to opt-in to receive notifications. If the user consents, Safari requests for its credentials on your Website in the form of a file called a push package. The push package also contains notification assets used throughout OS X and data used to communicate to a Web service that you must configure. If the push package is valid, you receive a unique identifier also known as device token for the user. The user receives the notification when you send the combination of this device token and your message, or payload to APNs.

This guide will hopefully help you in the process management and maintain a coherent way of getting your service implemented. What will be covered in small coherent steps:

Let us see how to implement your service:

  1. Generate your push certificate. You will require the Apple WWDRCA certificate provided by Apple from your developer portal to send notifications. Another certificate is needed when actually sending notifications and also while creating the push package. You will need two certificates.
    For registering app with APNs Establishing a Token-Based Connection to APNs
    This is not mentioned in Apple’s official documentation.

  2. Configure the raw push package folder, and then use the companion PHP file to zip up your final push package. We will also check for any issues while creating the push package in the debugging section.
    Your “push package” is a folder of icons and configurations that is used by each Mac device that subscribes to your notification service.

  3. Create a Webserver to verify your push package.

  4. Run the front end Javascript to subscribe to your notifications, and get the device token that is returned. Granting client access to your notifications is easy using Javascript. If a valid push package is returned, access is granted and a device token is given in a JSON response.

Generate Push Certificate

You must register in the Certificates, Identifiers & Profiles section of your developer account to send push notifications. You must have an Apple developer license to register.

  • Identifier - This is your unique reverse-domain string, such as web.com.example.domain (the string must start with web.). This is also known as the Website Push ID.
  • Website Push ID Description - This is the name used throughout the Provisioning Portal to refer to your website. Use it for your own benefit to label your Website Push IDs into a more human-readable format.
Webpush ID

Webpush ID

Webpush ID Description

Webpush ID Description

After the push ID is registered, create a production certificate of that push ID by clicking “Create Certificate” under “Edit your Identifier Configuration”.

If you already have the Certificate Signing Request, then upload the file from your local machine. If you do not, then see Apple Developer help to know how to create it.

You can download the push certificate after the CSR is uploaded:

Double click the downloaded certificate and add it to your keychain:

  1. Go to your Keychain > My Certificate,
  2. Select your certificate and private key.
  1. Export both as .p12.
  2. Add a password. This step is very important.

You will require one more certificate named “Apple Worldwide Developer Relations Certification Authority”. You can download it from the Apple Certification Authority.

Add AWDRCA certificate to the keychain and export it as .pem file.
Sign the push package with both the web push certificate and the intermediate certificate.

Create Push Package

When a user is asked for permission to receive push notifications, Safari asks your web server for a package. The package contains data that is used by the notification UI, such as your website name and icon, as well as a cryptographic signature. The signature verifies that your notification has not been intercepted by a man-in-the-middle attack and that it is indeed coming from a trusted source.

Below is the folder structure you must create:

pushpackage/
    icon.iconset/
        icon_16x16.png
        [email protected]
        icon_32x32.png
        [email protected]
        icon_128x128.png
        [email protected]
     manifest.json
     signature
     website.json
     
     

Website JSON

The website JSON dictionary named website.json contains metadata used by Safari and Notification Center to present UI to the user and to communicate with your web service.

Key
Description

websiteName

The website name. This is the heading used in the Notification Center.

websitePushID

The Website Push ID, as specified in your developer account.

allowedDomains

An array of websites that are allowed to request permission from the user.

urlFormatString

The URL to go to when the notification is clicked. Use %@ as a placeholder for arguments you fill in when delivering your notification. This URL must use the http or https scheme; otherwise, it is invalid.

authenticationToken

A string that helps you identify the user. It is included in later requests to your web service. This string must be 16 characters or greater.

webServiceURL

The location used to make requests to your web service. The trailing slash should be omitted.
This should be https.

Following is a sample valid website.json file:

{
    "websiteName": "Bay Airlines",
    "websitePushID": "web.com.example.domain",
    "allowedDomains": ["http://domain.example.com"],
    "urlFormatString": "http://domain.example.com/%@/?flight=%@",
    "authenticationToken": "19f8d7a6e9fb8a7f6d9330dabe",
    "webServiceURL": "https://example.com/push"
}



Iconset

The iconset is a directory called icon.iconset that contains PNG images in varying sizes. The images in your iconset populate the icons displayed to the user in the permission prompt, Notification Center, and the notification itself. Because your icon is static, it is unnecessary to include it in every push notification. Instead, your icons are downloaded once from your server and stored on the user’s computer.
The icons should be valid and as per Apple guidelines. Use https://tinypng.com/ to compress your icons to the required size.

Manifest

A manifest is a JSON dictionary named manifest.json that contains an entry for each file, where the local file path is the entry’s key, and a dictionary object is the entry’s value. This dictionary contains the hashType and hashValue, which is the file’s SHA512 checksum.

Signature

The signature is a PKCS #7 detached signature of the manifest file. Sign the manifest file with the private key associated with your web push certificate that you obtained while registering with Apple.

We will use a PHP file named createPushPackage.php to generate the zip file for the above pushpackage folder. The folder to create push package is present in the solution under the folder named “safari_push_package_creator”.

Step 1:
Copy and paste following files in one folder

  • .p12 certificate we created above by registering
  • PHP file
  • .pem file created using AWDRCA certificate
  • Create a tmp folder. Then pushPackage inside it.
    Step 2:
    Create one pushpackage.raw folder and paste following files in it
  • icon.iconset folder and all the icons mentioned above in it
  • Website.json as per the guidelines mentioned above
    Step 3:
    Open the PHP file and modify it as per the following instructions.
  • Change $certificate_path to path of .p12 certificate
  • Change $certificate_password to password of .p12 certificate
  • Replace "<path to .pem>" under create_signature with path to .pem file
  • Change $package_dir to path to tmp/pushPackage directory
    The AWDRCA.pem file is mandatory after 2014 for security purposes.
    Step 4:
    After the above steps are done, run the PHP file in the terminal
    php createPushPackage.php

If run successfully, under the tmp folder a pushPackage.zip file will be created. You can place this pushPackage.zip in your web service directory which will send the pushPackage.zip to the client when a request for safari push notifications will be requested.

Considerations

  • All the files must be present
  • Use the zipping method used in PHP file attached as the order of the files is also important
  • Icons must be valid
  • Use the valid certificates. If they expire, renew them.

Code Overview

Let us see the client-side and web-service code that returns the pushPackage.zip file to the client(safari browser).

Webserver

When Safari requests permission to display push notifications, an HTTPS request for credentials is sent to your Webserver. Configure a RESTful HTTPS web service on your Webserver to respond to these requests. The Web service can be hosted on any server or domain. The Webserver allows the request for push notification and sends a push package (application/zip format) to Safari. This push package is verified by Safari and it sends a push token to the CleverTap SDK.

Fragment
Description

webServiceURL

The URL to your web service; this is the same as the URL parameter in window.safari.pushNotification.requestPermission(). It must start with https.

version

The version of the API. Currently, “v1”.

deviceToken

The unique identifier for the user on the device.

websitePushID

The Website Push ID.

Configure endpoints in a RESTful https web service on your server to respond:
Step 1. Downloading Your Website Package
This POST request contains the following information:
The URL format is - webServiceURL/version/pushPackages/websitePushID
For example, https://yourwebsite.com/v1/pushPackages/web.com.yourwebsite
Step 2. Registering or Updating Device Permission Policy
This POST request contains the following information:
The URL format is - webServiceURL/version/devices/deviceToken/registrations/websitePushID
For example, https://yourwebsite.com/v1/devices/deviceToken/registrations/web.com.yourwebsite
Step 3. Forgetting Device Permission Policy
This DELETE request contains the following information:
The URL format is - webServiceURL/version/devices/deviceToken/registrations/websitePushID
For example, https://yourwebsite.com/v1/devices/deviceToken/registrations/web.com.yourwebsite
Step 4. Logging Errors
If an error occurs, a POST request is sent to the following URL:
The URL format is - webServiceURL/version/log
For example, https://yourwebsite.com/v1/log

Client side code

To request permission to send the user push notifications, call the window.safari.pushNotification.requestPermission() method.

Requesting permission is an asynchronous call.
window.safari.pushNotification.requestPermission(url, websitePushID, userInfo, callback);

A description of each argument is as follows:

  • URL - The URL of the web service, which must start with https. The Web server and the Website requesting permission can have different domains.
  • websitePushID - The Website Push ID, as specified in your developer account for the generated certificate. It follows the convention on Apple account it must start with web. For example, web.yourname.safari is a safari certificate id.
  • userInfo - An object required to pass to the server. Include any data in this object that helps you identify the user requesting permission.
  • callback - A callback function, which is invoked on completion.

Following is a sample code:

//For Safari
function requestPermission() {
    if ('safari' in window && 'pushNotification' in window.safari) {

        var permissionData =
            window.safari.pushNotification.permission('web.pjay.push');
        window.safari.pushNotification.requestPermission(
            'https://localhost:8443/Push_notification_war_exploded',
            'web.pjay.push', {}, function(subscription) {
                console.log(subscription);
                if(subscription.permission === 'granted') {
                    subscriptionInfoSafari = subscription;
                    safariToken = subscription.deviceToken;
                    sending(safariToken);
                    // updateSubscriptionOnServer(subscription);
                }
                else if(subscription.permission === 'denied') {
                    // TODO:
                }
            });

    } else {
        alert("Push notifications not supported.");
    }
}

Troubleshooting

If there is an issue with downloading the push package or delivery of push notifications, the logging endpoint on your Web service as described in Logging Errors is contacted with an error message and error description. The following table lists the possible errors and steps you can take to fix them:

Error Message
Resolution

AuthenticationToken must be at least 16 characters.

The authenticationToken key in your website.json file must be 16 characters or greater.

Downloading push notification package failed

The Safari push package could not be retrieved from the specified location.

Extracting push notification package failed

Check that your push package is zipped correctly.

Missing file in push notification package

Check that your push package contains all of the files specified in Building the Push Package

Missing image in push notification package

Check that your push package contains all of the files specified in the Iconset folder.

Missing key in website.json

Check that your website.json file has all of the keys listed in The Website JSON Dictionary.

Serialization of JSON in website.json failed

The website.json file in your push package is not valid JSON.

Signature verification of push package failed

The manifest was not signed correctly or was signed using an invalid certificate.

Unable to create a notification bundle for push notification package.

The extracted push package could not be saved to the user’s disk.

Unable to generate ICNS file for push notification package.

Your iconset may have malformed PNGs.

Unable to parse webServiceURL

Check that the value for webServiceURL in your website.json file is a valid URL.

Unable to save push notification package

The push package could not be saved to the user’s disk.

urlFormatString must have http or https scheme

Make sure that the value for urlFormatString in your website.json file starts with http or https.

Verifying hashes in manifest.json failed

The SHA512 checksums specified in your manifest.json file do not compute to their actual values.

Web Service API URL must be https.

Make sure that the URL at your push package endpoint starts with https.

webServiceURL must be equal to URL in call to requestPermission.

Cross-check that the web service URL in your JavaScript call matches the Web service URL in your website.json file.

websitePushID must be equal to identifier in call to requestPermission.

Cross-check that the identifier in your JavaScript call matches the identifier in your website.json file.

x cannot be used as a format string for URLs.

The URL created by inserting the notification payload’s url-args values into the placeholders specified in the push package’s urlFormatString is not valid, or there are a different number of values than placeholders.

Requesting User Permissions

This section is applicable for all browsers, that is, Chrome, Firefox, and Safari. Now that you have a service worker and manifest set up, it’s time to start asking users if they want to subscribe to Web pushes. For flexibility, CleverTap provides you with the ability to ask for notifications based on context and user actions.

As a general rule, we highly recommend asking for permission from users only after they’ve spent some time on your website, and completed action of significance. Do not ask new users to subscribe to notifications as soon as they land on your site.

For example, after a user has completed a transaction, you may call the function below.

clevertap.notifications.push({
  "apnsWebPushId":"<apple web push id>", //only for safari browser
  "apnsWebPushServiceUrl":"<safari package service url>",//only for safari browser
  "titleText":'Would you like to receive Push Notifications?',
  "bodyText":'We promise to only send you relevant content and give you updates on your transactions',
  "okButtonText":'Sign me up!',
  "rejectButtonText":'No thanks',
  "okButtonColor":'#f28046'});

The general format for creating the popup is below.

clevertap.notifications.push({
    "titleText":popupTitleText,
    "bodyText":popupBodyText,
    "okButtonText":okButtonText,
    "rejectButtonText":rejectButtonText,
    "okButtonColor":okButtonColorInHex});

Custom service worker format for notification permission popup

clevertap.notifications.push({
  
	"apnsWebPushId”: ‘<apple web push id>‘,
	"apnsWebPushServiceUrl”: ‘<safari package service url>’, 
   	"“titleText”:‘Would you like to receive Push Notifications?’,
   	"bodyText”:‘We promise to only send you relevant content and give you updates on your transactions’,
   	"okButtonText”:‘Sign me up!’,
   	"rejectButtonText”:‘No thanks’,
   	"okButtonColor”:‘#F28046’,
   	"askAgainTimeInSeconds”:5,
  	"serviceWorkerPath”: “/foo/my_sw.js” // path to your custom service worker file
  });

If a user blocks the native chrome permissions popup, the user is lost forever (unless the user clears their browser settings). However, if you are using the Clever popup, you get the advantage of asking the same user again for permission after a defined period.

Permission Frequency
To ensure that users are not asked for permission too frequently, our API ensures that calling clevertap.notifications.push does nothing if the user has rejected the dialog less than one week ago. Once a week has passed by, calling the function will display the dialog as expected. This eliminates the need for you to implement a separate check before calling the function.

To set a separate frequency, send "askAgainTimeInSeconds":time_in_seconds along with the above object.

To skip the Clever popup, send "skipDialog":true along with the above object.

Migrating from Other Services

This section is applicable for all browsers, that is, Chrome, Firefox, and Safari. If you are migrating from a different web push notifications provider, you may be concerned about asking subscribed users to enable notifications a second time.

Note that, if a user has already enabled notifications on your host domain, calling clevertap.notifications.push will not display the popup for that particular user, and the registration will automatically be migrated to our new implementation.

You can use the below custom service file which should only be used during the migration phase. Once the token migration of most of your users is complete, you can replace it with the parent service worker.

importScripts('https://s3-eu-west-1.amazonaws.com/static.wizrocket.com/js/sw_webpush_only_registration.js');

Debugging

This section is applicable for all browsers, that is, Chrome, Firefox, and Safari.
Error messages and warnings are logged to the JS console of the browser.

Verbose logging: enable verbose logging of all communication with the CleverTap servers by setting the WZRK_D variable in sessionStorage. In the developer console of your browser type: sessionStorage['WZRK_D'] = '';

Updated 12 days ago


Web


Suggested Edits are limited on API Reference Pages

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