To proceed with the integration of Web Push SDK to your HTTPS website, you should do the following:
Locate your Pushwoosh Application Code.
Chrome and Firefox: locate your Firebase API key and Sender ID. To do so, please follow steps 1-3 of Chrome and Firefox Configuration guide.
Safari: locate your Website Push ID.
Download Pushwoosh Web Push SDK.
Chrome pushes will not work with self-signed certificates (https/ssl). You'll need SSL certificate signed by trusted Authority.
Push notifications don't work in both Incognito and Guest mode.
Auto subscription is not available for Safari.
Integration sample on GitHub
1. Get Pushwoosh Web Push SDK and unzip it. You should have the following files:
manifest.json
pushwoosh-service-worker.js
2. Open manifest.json and make the following changes:
2.1. Change name
and short_name
to the name of your website.
2.2. Change gcm_sender_id
to your Sender ID. Please keep in mind that Sender ID is usually a 12-digit number, and it can't contain any letters.
3. Place all these files to top-level root of your website directory.
Make sure the following URLs are publicly accessible:
4. Initialize the SDK:
4.1. Include manifest.json in <head>
(not <body>
).
Make sure <link rel="manifest" href="/manifest.json">
is located above other <link rel="manifest" ...>
in the <head>
, or it won't be found.
4.2. Include the SDK from our CDN asynchronously.
Click here if you are using Google Tag Manager.
<script type="text/javascript" src="//cdn.pushwoosh.com/webpush/v3/pushwoosh-web-notifications.js" async></script>
4.3. Initialize the Web Push SDK and make sure to queue the initialization until the moment the SDK is fully loaded.
<script type="text/javascript">var Pushwoosh = Pushwoosh || [];Pushwoosh.push(['init', {logLevel: 'info', // possible values: error, info, debugapplicationCode: 'XXXXX-XXXXX', // you application code from Pushwoosh Control PanelsafariWebsitePushID: 'web.com.example.domain', // unique reverse-domain string, obtained in you Apple Developer Portal. Only needed if you send push notifications to Safari browserdefaultNotificationTitle: 'Pushwoosh', // sets a default title for push notificationsdefaultNotificationImage: 'https://yoursite.com/img/logo-medium.png', // URL to custom custom notification imageautoSubscribe: false, // or true. If true, prompts a user to subscribe for pushes upon SDK initializationsubscribeWidget: {enabled: true},userId: 'user_id', // optional, set custom user IDtags: {'Name': 'John Smith' // optional, set custom Tags}}]);</script>
To prompt your users to subscribe for push notifications, we recommend implementing a push subscription button on your website. Enhance user experience and get more subscribers!
To finish implementing push notifications into your website, you need to configure web platforms in your Pushwoosh Control Panel following our step-by-step guides:
To get FCM sender ID and API Key, please follow steps 1-3 of the Android configuration guide.
Sometimes you can't place the service worker file in a root directory of a website but in a subdirectory. Here's the steps you should take to integrate Pushwoosh Web SDK in this case:
If you can place the files in a subdirectory of your website only, for example, yourdomain.com/push-notifications. Place manifest.json and pushwoosh-service-worker.js into the subdirectory and follow the steps 2 - 4.2 of the standard guide.
Modify the configuration (step 4.3) by adding a parameter serviceWorkerUrl: “/push-notifications/pushwoosh-service-worker.js”
where /push-notifications/pushwoosh-service-worker.js
is the path to pushwoosh-service-worker.js
file.
Add the mechanism that redirects users to this subdirectory on your site like yourdomain.com/push-notifications/index.html. Make sure to set up our SDK in the subdirectory as well!
Add the button that registers users for pushes. Use this guide to implement the subscription button.
Alternatively, you can use auto subscription using autoSubscribe: true
parameter of Web SDK initializer.
Use the Event listener onPermissionGranted
(reference) in order to redirect user back to the main page when he succeeded with the subscription.
In Pushwoosh Web SDK 3.0 you can subscribe to certain events to track them. The first argument in each callback is an API object.
onReady// Executed after successful SDK initialization.Pushwoosh.push(['onReady', function(api) {console.log('Pushwoosh ready');}]);
A bit easier way to subscribe to onReadyPushwoosh.push(function(api) {console.log('Pushwoosh ready');});
onSubscribe// Executed after a user agrees to receive push notifications.Pushwoosh.push(['onSubscribe', function(api) {console.log('Event: onSubscribe triggered');}]);
onUnsubscribe// Executed after a device is unregistered from notifications.Pushwoosh.push(['onUnsubscribe', function(api) {console.log('Event: onUnsubscribe triggered');}]);
Track displaying of native subscription dialog.
onShowNotificationPermissionDialog// Executed on permission dialog displayingPushwoosh.push(['onShowNotificationPermissionDialog', function(api) {console.log('EVENT: onShowNotificationPermissionDialog');}]);
onHideNotificationPermissionDialog// Executed on hiding the permission dialog with one of three possible statuses:// 1. default - the dialog is closed// 2. granted - permission is granted// 3. denied - permission is deniedPushwoosh.push(['onHideNotificationPermissionDialog', function(api, permission) {console.log('EVENT: onHideNotificationPermissionDialog', permission);}]);
Track displaying of a Subscription Prompt widget.
onShowSubscriptionWidget// Executed on displaying of the Subscription Prompt widgetPushwoosh.push(['onShowSubscriptionWidget', function(api) {console.log('EVENT: onShowSubscriptionWidget');}]);
onHideSubscriptionWidget// Executed on hiding of the Subscription Prompt widgetPushwoosh.push(['onHideSubscriptionWidget', function(api) {console.log('EVENT: onHideSubscriptionWidget');}]);
Check the push notifications permission's status on SDK initialization; track the update of this status whenever it takes place.
onPermissionPrompt// Executed during the SDK initialization if 'autoSubscribe: false' or/and if a user ignores a push notification promt.Pushwoosh.push(['onPermissionPrompt', function(api) {console.log('Event: onPermissionPrompt triggered');}]);
onPermissionDenied// Executed during the SDK initialization if notifications are blocked or once a user blocks push notifications.Pushwoosh.push(['onPermissionDenied', function(api) {console.log('Event: onPermissionDenied triggered');}]);
onPermissionGranted// Executed during the SDK initialization if notifications are allowed or once a user allows push notifications.Pushwoosh.push(['onPermissionGranted', function(api) {console.log('Event: onPermissionGranted triggered');}]);
Once your user clicks on the notification, you can get and process the custom data passed with this push. To process the payload, you should use the onNotificationClick
event:
Pushwoosh.push('onNotificationClick', function(api, payload) {const {url,messageHash,campaignCode,customData // JSON} = payload;});
You can also find the additional information about the push notification, such as the message hash or the URL that was opened once user had clicked the notification.
Callbacks for the listeners below have two parameters:
An API object
Push notification payload
onPushDelivery// Executed when a push notification is displayed.Pushwoosh.push(['onPushDelivery', function(api, payload) {console.log('Event: onPushDelivery triggered', payload);}]);
onPushDelivery payload examplevar payload = {title: 'Notification Title',body: 'Notification text message',icon: 'https://yoursite.com/img/logo-medium.png',openUrl: 'https://yoursite.com/some/path',messageHash: '2m',customData: {foo: 'bar'}};
onNotificationClick// Executed when a user clicks on notification.Pushwoosh.push(['onNotificationClick', function(api, payload) {console.log('Event: onNotificationClick triggered', payload);}]);
onNotificationClick payload examplevar payload = {url: 'https://yoursite.com/some/path',messageHash: '2m',customData: {foo: 'bar'}};
onNotificationClose// Executed when a push notification is closed.Pushwoosh.push(['onNotificationClose', function(api, payload) {console.log('Event: onNotificationClose triggered', payload);}]);
onNotificationClose payload examplevar payload = {url: 'https://yoursite.com/some/path',messageHash: '2m'};
onUpdateInboxMessages// Executed after the Inbox is updated automatically while the page is loading.Pushwoosh.push(['onUpdateInboxMessages', function(api, pwinbox) {pwinbox.loadMessages().then(function(messages) {console.log('EVENT: onUpdateInboxMessages', messages);});}]);
onPutNewMessageToInboxStore// Executed by ServiceWorker after the Inbox Message is received and saved to indexedDB.Pushwoosh.push(['onPutNewMessageToInboxStore', function(api, message) {console.log('EVENT: onPutNewMessageToInboxStore', message);}]);
After the Web Push SDK is initialized, you can make the following calls to Pushwoosh API. All the methods return Promise objects.
Pushwoosh.push(function(api) {// Set tags for a userapi.setTags({'Tag Name 1': 'value1','Tag Name 2': 'value2'});// Get tags for a user from serverapi.getTags();// Register user IDapi.registerUser('myUserID');// Post an Eventapi.postEvent('myEventName', {attributeName: 'attributeValue'});//Unregister from notificationsapi.unregisterDevice();});
Example of sending Tags to Pushwoosh:
Pushwoosh.push(function(api) {var myCustomTags = {'Tag 1': 123,'Tag 2': 'some string'};api.setTags(myCustomTags).then(function(res) {var skipped = res && res.skipped || [];if (!skipped.length) {console.log('success');}else {console.warn('skipped tags:', skipped);}}).catch(function(err) {console.error('setTags error:', err);});});
To increment a value of a Number Tag, use the operation
parameter with the ‘increment’ value as follows:
Pushwoosh.push(function(api) {api.setTags({'Tag 1': {operation: 'increment',value: 1}})});
To append new values to the existing List Tag, use the operation
parameter with the ‘append’ value as follows:
Pushwoosh.push(function(api) {api.setTags({'Tag 3': {operation: 'append',value: ['Value3']}})});
To remove a value from a List Tag, use the operation
parameter with the ‘remove’ value as follows:
Pushwoosh.push(function(api) {api.setTags({'Tag 3': {operation: 'remove',value: ['Value2']}})});
Please note that auto subscription is not available for Safari users. Please consider subscribing Safari users to push notifications by calling the Pushwoosh.subscribe()
method.
Pushwoosh.subscribe()
This method is used to request a user's permission for push notifications. If a user is already subscribed, the method will stop executing.
If a user hasn’t subscribed for pushes yet:
1. Permission for push notifications is requested.
2. If a user allows notifications, onSubscribe
event is triggered.
Pushwoosh.subscribe()
is executed automatically if autoSubscribe: true
. is set during the SDK initialization.
Call this method if you have chosen to manually prompt a user to subscribe for pushes using the autoSubscribe: false
parameter during the initialization:
<button onclick="Pushwoosh.subscribe()">Subscribe</button><script>Pushwoosh.push(['onSubscribe', function(api) {console.log('User successfully subscribed');}]);</script>
Pushwoosh.unsubscribe()
/unregisterDevice
method is executed.
onUnsubscribe
event is triggered.
<button onclick="Pushwoosh.unsubscribe()">Unsubscribe</button><script>Pushwoosh.push(['onUnsubscribe', function(api) {console.log('User successfully unsubscribed');}]);</script>
Pushwoosh.isSubscribed()
Checks if a user is subscribed and returns true/false flag.
Pushwoosh.isSubscribed().then(function(isSubscribed) {console.log('isSubscribed', isSubscribed);});
Pushwoosh.getHWID()
Returns Pushwoosh HWID.
Pushwoosh.getHWID().then(function(hwid) {console.log('hwid:', hwid);});
Pushwoosh.getPushToken()
Returns push token if it is available.
Pushwoosh.getPushToken().then(function(pushToken) {console.log('pushToken:', pushToken);});
Pushwoosh.getUserId()
Returns User ID if available.
Pushwoosh.getUserId().then(function(userId) {console.log('userId:', userId);});
Pushwoosh.getParams()
Returns a list of the following parameters:
Pushwoosh.getParams().then(function(params) {params = params || {};var hwid = params.hwid;var pushToken = params.pushToken;var userId = params.userId;});
Pushwoosh.isAvailableNotifications()
Checks if a browser supports the Pushwoosh WebSDK 3.0, returns ‘true’ or ‘false’.
Pushwoosh.isAvailableNotifications() // true/false
messagesWithNoActionPerformedCount(): Promise<number>
Returns the number of opened messages.
Pushwoosh.pwinbox.messagesWithNoActionPerformedCount().then((count) => {console.log(`${count} messages opened`);});
unreadMessagesCount()
Returns the number of unread messages.
Pushwoosh.pwinbox.unreadMessagesCount().then((count) => {console.log(`${count} messages unread`);});
messagesCount(): Promise<number>
Returns the total number of messages.
Pushwoosh.pwinbox.messagesCount().then((count) => {console.log(`${count} messages`);});
loadMessages(): Promise<Array>
Loads the list of undeleted messages.
Pushwoosh.pwinbox.loadMessages().then(() => {console.log('Messages have been loaded');});
readMessagesWithCodes(codes: Array<string>): Promise<void>
Marks messages as read by Inbox_Ids.
Pushwoosh.pwinbox.readMessagesWithCodes(codes).then(() => {console.log('Messages have been read');});
performActionForMessageWithCode(code: string): Promise<void>
Performs the action assigned to a message and marks the message as read.
Pushwoosh.pwinbox.performActionForMessageWithCode(code).then(() => {console.log('Action has been performed');});
deleteMessagesWithCodes(codes: Array<string>): Promise<void>
Marks messages as deleted.
Pushwoosh.pwinbox.deleteMessagesWithCodes([code]).then(() => {console.log('Messages have been deleted');});
syncMessages(): Promise<void>
Synchronizes messages with the server.
Pushwoosh.pwinbox.syncMessages().then(() => {console.log('Messages have been synchronized');});
To integrate Pushwoosh into your Progressive Web Application (PWA), follow the steps described below.
1. Copy the path to your Service Worker file:
if ('serviceWorker' in navigator) {window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js') // <- your service worker url});}
Then, use the serviceWorkerUrl parameter while initializing the WebSDK as follows:
var Pushwoosh = Pushwoosh || [];Pushwoosh.push(['init', {logLevel: 'error',applicationCode: 'XXXXX-XXXXX',safariWebsitePushID: 'web.com.example.domain',defaultNotificationTitle: 'Pushwoosh',defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',serviceWorkerUrl: '/service-worker.js', // <- your service worker url}]);
WebSDK does not register the new Service Worker immediately; a Service Worker is registered when it's needed:
when a device receives a push token (on device registration or re-subscription),
when a push token is deleted (on removing a device from user base).
It speeds your pages loading by shortening the number of server requests.
Browsers do not allow two different Service Workers to be registered at the same time (read more: https://github.com/w3c/ServiceWorker/issues/921), so to make your PWA work correctly, a common Service Worker should be registered for your codebase and the Pushwoosh codebase.
2. Add the following string to your Service Worker (at the beginning or at the end of, it doesn’t matter):
importScripts('https://cdn.pushwoosh.com/webpush/v3/pushwoosh-service-worker.js' + self.location.search);
Thus you enable receiving and processing of push notifications sent via Pushwoosh services for your Service Worker.
Pushwoosh won't affect your codebase. You can always check out our Service Worker at https://github.com/Pushwoosh/web-push-notifications.
ServiceWorker compatible with a package version is located in node_modules/web-push-notifications/lib/service-worker.js
only for Web Push SDK 3.2.7 and higher. Please note that interactions between Web Push SDK and ServiceWorker could differ for different versions, so it’s essential to use the ServiceWorker compatible with the Web Push SDK version you use.
Install Web Push SDK as a node module and save it as a dependency in your package.json:
Shellnpm install web-push-notifications --save
CommonJS modulesvar Pushwoosh = require('web-push-notifications').Pushwoosh;var pwInstance = new Pushwoosh();pwInstance.push(['init', {logLevel: 'info', // or debugapplicationCode: 'XXXXX-XXXXX',safariWebsitePushID: 'web.com.example.domain',defaultNotificationTitle: 'Pushwoosh',defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',autoSubscribe: true,userId: 'user_id',tags: {'Name': 'John Smith'}}]);
Load WebPushSDK with ES6 modulesimport {Pushwoosh} from 'web-push-notifications';const pwInstance = new Pushwoosh();pwInstance.push(['init', {logLevel: 'info', // or debugapplicationCode: 'XXXXX-XXXXX',safariWebsitePushID: 'web.com.example.domain',defaultNotificationTitle: 'Pushwoosh',defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',autoSubscribe: true,userId: 'user_id',tags: {'Name': 'John Smith'}}]);
Make sure to follow this guide's steps 1 to 4 before adding the script to Google Manager Tag!
Use the following code in your Google Tag Manager to initialize Pushwoosh SDK. Create a Custom HTML Tag and paste the code below. Make sure to change your Pushwoosh Application Code, Safari Website ID, and default notification image URL. Also set high Tag Firing priority (ex: 100) and trigger it on All Pages. See below for a screenshot.Copy
<script type="text/javascript" src="//cdn.pushwoosh.com/webpush/v3/pushwoosh-web-notifications.js" async></script><script type="text/javascript">var Pushwoosh = Pushwoosh || [];Pushwoosh.push(['init', {logLevel: 'error',applicationCode: 'XXXXX-XXXXX',safariWebsitePushID: 'web.com.example.domain',defaultNotificationTitle: 'Pushwoosh',defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png',autoSubscribe: true,subscribeWidget: {enable: false},userId: 'user_id'}]);</script>