This article provides developers information for configuring websites to receive Web Push notifications sent from the Emarsys platform.
Introduction
Web Push Notification is a push message contacts receive in the desktop or mobile browser. Push Notification Message will appear on the active browser or on the desktop if the browser is minimised. If the browser is closed, the message will be queued until the browser comes online. The primary use of browser notifications to engage with contacts even when they are not on the customer's site. Web Push Notifications can also be referred to as Browser Push Notifications. Web Push notifications work on Android mobile browsers but not on iPhones due to a limitation set by Apple.
Web Push notifications are different from mobile push notifications as Web Push messages are sent to the browser, whereas mobile push notifications are sent to the mobile app. If you are interested in mobile app push notifications, please refer to our Mobile Engage documentation.
Supported Browsers
Confirmed below are the list of browsers the Emarsys web SDK supports web push notifications
Desktop
- Chrome v53+
- Firefox v22+
- Opera v39+
- Safari v11+
- Microsoft Edge v26+
Mobile
- Firefox Android v26+
- Chrome Android v53+
- Opera Android v41+
The 2 types of Web Push notification sending mechanism supported are VAPID (Voluntary Application Server Identity) and APNS (Apple Push Notification Service). Most browsers now support VAPID authentication, including but not limited to; Chrome, Firefox, Opera and Edge. Currently, Safari browsers do not support VAPID and instead use APNS.
It is not possible to use Web push notifications in both incognito or guest mode.
Web Push notifications do not work on iOS devices due to a limitation set by Apple.
You need to access the root directory of the related web page to implement Web Push Notifications. For more information, see Service Worker.
Standard Implementation Steps
The steps detailed below are to implement and enable the Web Push feature. To aid the implementation, you will find a sample index file below that you can use as a reference when implementing.
Setting up the domain in Emarsys
To allow the Web SDK to connect to Emarsys, the domain needs to be added to the Emarsys account. Please login to the Emarsys account and navigate to Channels > Web Push > Domains tab.
Click on the Create Domain button at the top right of the screen.
Enter the Domain name and Default language:
- Domain Name - The name if the app set on the previous section.
- Default language - The default language of the app.
Click Save.
Take a note of the Domain code as this will be used later in the integration.
Add the VAPID key (for Chrome, Firefox etc browsers) by clicking on Add VAPID under the Platform section. Then enter the Private and Public keys, followed by Save.
It is recommended to generate a new VAPID key, even if there was one used with a previous provider. There are numerous tools online to generate them. There is no particular recommendation for a VAPID key generator.
Add the APNS certificate (for Safari) by clicking on Add APNS. Followed by uploading the .p12 file, enter the passphrase used when generating the .p12 file, and click Save.
It is recommended to generate a new APNS key, even if there was one used with a previous provider. The guide to achieve this on the Emarsys Help Portal here
Service Worker
A service worker is a script that the browser runs in the background, separate from the web page. The task of the service worker is to receive the push event. If you already have a service worker for the website, import the Emarsys service worker to it by adding the following line to the current service worker file.
self.importScripts("https://assets.emarsys.net/web-emarsys-sdk/<VERSION>/web-emarsys-service-worker.js")
Should the website not have a service worker file, please create a file called "service-worker.js", add the line of code shown above and place the file in the root directory of the website.
The Service Worker file needs to be stored on the root directory of the website.
Please note that at the time of this publication of this document, the version is 4.3.1 but it may be updated in the future. To find the latest version, please use the cURL command below:
curl --head https://redirector.eservice.emarsys.net/web-emarsys-sdk/latest/
Salesforce Commerce Cloud
Clients that use the Salesforce Commerce Cloud do not have access to the root directory to place the Service Worker. However, it is possible to remap the Service Worker on Salesforce Commerce Cloud so that Web Push will work. The steps for this are below:
- In Salesforce, create a Salesforce Commerce Cloud object with the type 'Content Asset'.
- Add the Emarsys service worker code to it, as detailed above.
- Create an alias of the route to the service worker by going to Business Manager > Merchant Tools > SEO > Aliases.
- Enter in the example below:
{...
"host-name" : \[
...,
{
"if-site-path": "/web-emarsys-service-worker.js",
"pipeline": "[name of SFCC object created in step 1]"
}
\]
}
5. Check that the service worker is available by going to https://[CustomerDomain]/web-emarsys-service-worker.js
Website page
Initialise the SDK by loading the SDK file asynchronously and queue the initialisation until the SDK file is fully loaded by placing the following in the Head tag of the website HTML.
<script type="text/javascript" src="https://assets.emarsys.net/web-emarsys-sdk/<VERSION>/web-emarsys-sdk.js" async></script>
<script type="text/javascript">
var WebEmarsysSdk = WebEmarsysSdk || []
WebEmarsysSdk.push(['init', {
applicationCode: 'XXXXX-XXXXX', // your Domain code obtained above
safariWebsitePushID: 'web.com.yoursite.example', // unique reverse-domain string, obtained in you Apple Developer Portal
defaultNotificationTitle: 'Your Default Title', // sets your default title for push notifications
defaultNotificationIcon: 'https://yoursite.com/img/your-logo.png', // URL to your notification icon
autoSubscribe: false, // If true, prompts a user to subscribe for pushes upon SDK initialization which is not recommended
serviceWorker: {
url: 'service-worker.js',
applicationServerPublicKey: 'your-public-vapid-key'
}
}])
</script>
-
safariWebsitePushID
is only required if it is desired to send push notifications to Safari browsers. -
defaultNotificationTitle
is used when the title of the Web Push message is not defined in the campaign.- The default title is overridden by the campaign title when it is present.
- For the default title, please avoid using anything particular to a specific campaign or parent company, but use a title related to the brand or main topic of the website instead.
- For example: if a parent company owns multiple brands and websites that collect Web Push subscribers, users who may not know the parent company's name will be confused when receiving the message.
-
defaultNotificationIcon
: Use PNG format for the default icon.
- Please make sure the SDK version on the page, matches that of the Service Worker. In other words, if the present SDK version is 4.3.1, then both the Service Worker and the web SDK entered on the page state 4.3.1 for the version.
- At the time of this publication of this document, the version is 4.3.1 but it may be updated in the future. To find the latest version, please use the cURL command below:
curl --head https://redirector.eservice.emarsys.net/web-emarsys-sdk/latest/
Contact Management
The public functions detailed below should only be used after the SDK has completed initialisation.
The functions described in this section allow customer to manage the linking of browsers to the Emarsys account, to allow push notifications to be sent to contacts. Prior to following the steps below, it is beneficial to understand the anonymous versus the known contact record concept Emarsys uses to manage records.
- Anonymous Contact - An anonymous contact record is basically a device record and is created when a user subscribes to web push notifications for the first time when the platform receives a call from the web push SDK. When the record is created, a hardware ID is assigned that is used to stop duplicate records being created, should the user return to the website.
Deleted contacts data will be removed and will not receive push notifications. They need to subscribe again to receive push messages.
- Known Contact - A known contact is a record that already exists in the Emarsys account. This record is created and maintained by contact sync implemented for the entire account. The contact sync should have already been established prior to implementing the web push SDK. Please note that the Emarsys web SDK does not create known contact records, it only connects the device to the pre-existing known contact record.
Subscribe
Safari and Firefox require an event to happen on the page prior to requesting the user permission. Triggering the call prior to an event on the page will result in the request failing. An event can be any click on the page. It is expected that other browsers, for example Chrome, will soon have a similar requirement.
Use the subscribe
method to request to send push notifications to the contact. If the contact has already subscribed, the method will just return.
function subscribe (): Promise<void>;
When a contact grants permission to receive push notifications, the callback onSubscribe
will be invoked.
An example of requesting the user subscribe after a click on the page is provided below:
// Subscribe on button click
<button onclick="generalSubscribe()">Subscribe</button>
<script>
function generalSubscribe() {
return WebEmarsysSdk.subscribe()
}
// The submit event fires when a <form> is submitted.
document.addEventListener('submit', function(e) {
generalSubscribe();
});
// An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
document.addEventListener('click', function(e) {
generalSubscribe();
});
</script>
Unsubscribe
Use the unsubscribe
method to disable push notifications for a contact. An example where this call may be placed would be on a preferences page, where the user could configure the channels allowed to communicate with them.
function unsubscribe (): Promise<void>;
Contact Link
To link the browser to a known contact record in Emarsys, use the login
function. For that you must include the fieldId
and fieldValue
in the call. You will find the fieldId
by navigating to the Field Editor in the Emarsys account (Management > Field Editor).
Setting the fieldId
to any field that contains PII data (like email or hashed email) is prohibited. Using such fieldId
may result in this data being stored in our cloud infrastructure, which is not allowed.
Please set the fieldId
to unique, non-guessable and immutable contact identifiers (email or hashed email is not allowed). For example, Customer IDs are considered non-PII and are safe to use.
function login (contactInfo?: ContactInfo): Promise<boolean>;
type ContactInfo = {
fieldId: number,
fieldValue: string
}
Contact Unlink
To unlink a known contact record from the browser, e.g. the user logs out of the account and the push communications are private/sensitive, use the logout
function. The anonymous contact record will continue to be linked to the browser.
function logout (): Promise<boolean>;
Custom events
Custom events cannot be deleted and therefore should not contain any PII data.
You can use the customEvent
method to fire a custom event, which can be used for tracking or triggering an Automation program (Automation Center or Interactions).
When implementing, the eventName
parameter is required.
WebEmarsysSdk.customEvent(<eventName: String>)
The event will be available in the Automation program as soon as the first event is triggered by contacts.
Using a custom event to trigger an Interactions program
Here is what you need to do to fire a custom event that triggers an Interactions program when contacts perform a specific action on your website:
1. Add the code below to the website action that will trigger the custom event where eventName
is the name of your custom event:
WebEmarsysSdk.customEvent('eventName', { k1: 'v1', k2: 'v2' }).then((success) => {
console.log('Sending custom event result:', success)
}).catch(err => {
console.error('Error during custom event sending', err)
})
2. You can select the specific event in the Web Push event trigger in your Interactions program.
The event will be available in Interactions as soon as contacts trigger it.
Payload example
{"dnd":true,"events":
[{"type":"custom","name":"MCTestEvt","timestamp":"2022-01-17T09:57:20.121Z"}],
"clicks":[],"viewedMessages":[]}
Additional Functions
The additional functions detailed below are to provide developers greater control and flexibility as to when implementing the web push feature.
isSubscribed
Returns a boolean indication if the web browser and user is fully registered. This is the case if:
- The user granted the allowance for receiving push notifications (has a push token),
- The browser is registered in our backend and
- The user is logged in.
function isSubscribed (): Promise<boolean>;
getLoggedInContact
Returns the information about the contact which is currently linked to the browser.
function getLoggedInContact (): Promise<ContactInfo | {} | undefined>;
Returns one of the following
- The
ContactInfo
consisting of thefieldId
andfieldValue
if the contact record linked to the browser is that of a known contact. - An empty object {} if the contact record linked to the browser is anonymous.
- Undefined if there is neither a known nor the anonymous contact linked to the browser.
Event Listeners
To register a callback function you have to use the public push method of the SDK and you should register all of your callbacks in a <script>
part which is placed at the end of the website HTML.
type HandlerFn = (params?: any) => any
type SdkOnReadyCallback = HandlerFn
type SdkInitCallback = ['init', IInitParams]
type WebSdkEvent = 'onReady' | 'onSubscribe' | 'onUnsubscribe' | 'onSWInitError' | 'onPermissionPrompt' | 'onPermissionDenied' | 'onPermissionGranted'
type WebSdkEventCallback = [WebSdkEvent, HandlerFn]
type SdkCommand = SdkInitCallback | SdkOnReadyCallback | MeWebSdkEventCallback
function push (sdkCommand: SdkCommand): void;
init
Is invoked after the web page and SDK code are fully loaded. The init
callback is part of the SDK. The initialisation parameters are required to be passed to the push method.
type SdkInitCallback = ['init', IInitParams]
type SdkCommand = SdkInitCallback | ...
function push (sdkCommand: SdkCommand): void;
onReady
The onReady
callback is invoked after the SDK has been initialised. It is possible to register the desired callback by passing a function to the push method or use the same approach which can be used for all other supported events.
<script>
WebEmarsysSdk.push(function() {
console.log('EVENT: onReady');
// do whatever you need to do after the SDK is ready
});
// further event handler registrations...
</script>
Further Events
All callbacks for events listed in this section have to be registered by passing an array object to the push method, which consists of the event name and the callback function.:
-
onSubscribe
: Invoked when the browser is registered with our backend and we have a push token and a user is linked to the browser. -
onUnsubscribe
: Invoked after the successful execution of unsubscribe. -
onSWInitError
: Invoked in case there was an error detected during the registration of the service worker (SW). -
onPermissionPrompt
: Invoked when it is necessary to prompt the user for allowance of push notifications. -
onPermissionDenied
: Invoked when the user generally denied reception of push notifications. -
onPermissionGranted
: Invoked when the user granted the reception of push notifications.
<script>
// ...
WebEmarsysSdk.push(['onPermissionPrompt', function() {
console.log('EVENT: onPermissionPrompt');
}]);
</script>
Troubleshooting
In the event that the push messages are not received, the first suggested checks would be the device operating system settings and the browser settings.
- When checking the operating system, please check that Do Not Disturb is disabled in the System Preferences/Settings of the operating system.
- When checking the browser settings, please check that the site is permitted to send notifications.
It is worth noting that if you are testing push notifications while on a virtual meeting (e.g. using Zoom, Microsoft Teams etc.), the meeting software may have enabled do not disturb at the start of the meeting automatically and without your knowledge.