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 the desktop if the browser is minimized. 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 differ 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 is 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+
- Safari v16.4+
The 2 types of Web Push notification-sending mechanisms supported are VAPID (Voluntary Application Server Identity) and APNS (Apple Push Notification Service). Most browsers, including Chrome, Firefox, Opera, Safari and Edge, now support VAPID authentication.
Please note that using Web push notifications in browsers in both incognito and guest mode is not possible.
You need to access the root directory of the related web page to implement Web Push Notifications. For more information, see Service Worker.
Web push is known to have an issue with Safari 17.3 and 17.4 ICNS using APNS. Because the mentioned browsers may be unable to generate ICNS files for the push notification package, we suggest using VAPID for Safari for macOS (only applicable to Safari 16 or later) and setting the flag enableMacSafariVapid
to true
until further notice from Apple.
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.
- Log in to the Emarsys account and navigate to Channels > Web Push > Domains tab.
- Click the Create Domain button at the top right of the screen.
- Enter the Domain name and Default language:
- Domain Name - The name of the app set in the previous section.
- Default language - The app's default language.
- Click Save.
Take a note of the Domain code, which will be used later in the integration.
- Under Platform, click Add VAPID to add the VAPID key (for Chrome, Firefox, etc.). Then, enter the Private and Public keys and Save.
It is recommended to generate a new VAPID key, even if one was used with a previous provider. Numerous tools are available online to generate them. There is no particular recommendation for a VAPID key generator.
- Click Add APNS to add the APNS certificate (for Safari). Then, upload the .p12 file, enter the passphrase used when generating it, 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 is available on the Emarsys Help Portal here.
Service Worker
A Service Worker is a script 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 by adding the following line to the current service worker file.
self.importScripts("https://client-version.cf.emarsys.net/web-emarsys-sdk-v4/latest/web-emarsys-service-worker.js")
If the website does not have a Service Worker file, create a file called service-worker.js
, add the line of code shown above, and place the file in the website's root directory.
The Service Worker file must be stored in the website's root directory.
Please note that at the time of the publication of this document, the version is 4 but it may be updated in the future.
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
Initialize the SDK by loading the SDK file asynchronously and queue the initialization until the SDK file is fully loaded by placing the following in the website HTML's head
tag.
<script type="text/javascript" src="https://client-version.cf.emarsys.net/web-emarsys-sdk-v4/latest/web-emarsys-sdk.js" async></script>
<script type="text/javascript">
var WebEmarsysSdk = WebEmarsysSdk || []
WebEmarsysSdk.push(['init', {
applicationCode: 'XXXXX-XXXXX', // your Domain code obtained above
enableMacSafariVapid: true, // If true, enables VAPID instead of APNS for Safari on Mac
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 you would like 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 and instead use a title related to the brand or main topic of the website.
- 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 ensure the SDK version on the page matches the Service Worker's. In other words, if the present SDK version is 4, then both the Service Worker and the web SDK entered on the page state 4 for the version.
- At the time of this document's publication, the version is 4 but it may be updated in the future.
Contact Management
The public functions detailed below should only be used after the SDK has completed initialization.
The functions described in this section allow customers to manage the linking of browsers to the Emarsys account, enabling push notifications to be sent to contacts. Before following the steps below, it is beneficial to understand the anonymous versus known contact used by Emarsys to manage records.
-
Anonymous Contact - An anonymous contact record is basically a device record created when a user subscribes to web push notifications for the first time and the platform receives a call from the web push SDK. When the record is created, a
hardware ID
is assigned that is used to prevent duplicate records from 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 occur on the page prior to requesting the user's 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, such as Chrome, will soon have a similar requirement.
Use the subscribe
method to request that push notifications be sent 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
Use the login
function to link the browser to a known contact record in Emarsys. 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 fieldValue
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
Use the logout
function to unlink a known contact record from the browser. For example, if the user logs out of the account and the push communications are private or sensitive, 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 to track or trigger 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 contacts trigger the first event.
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 intended to give developers greater control and flexibility when implementing the web push feature.
isSubscribed
Returns a boolean indication if the web browser and user are fully registered. This is the case if:
- The user is 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
consists 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 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
It is invoked after the web page and SDK code are fully loaded. The init
callback is part of the SDK. The initialization parameters must 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 initialized. You can register the desired callback by passing a function to the push method or using the same approach that 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 must be registered by passing an array object to the push method, consisting of the event name and the callback function:
-
onSubscribe
: Invoked when the browser is registered with our backend, we have a push token and a user is linked to the browser. -
onUnsubscribe
: Invoked after the successful execution of unsubscribe. -
onSWInitError
: Invoked if an error was detected during the Service Worker's (SW) registration. -
onPermissionPrompt
: Invoked when it is necessary to prompt the user to allow 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
If the push messages are not received, the first suggested checks are the device operating system settings and 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 automatically and without your knowledge at the start of the meeting.