Javascript SDK reference
You can use the Javascript SDK to subscribe a browser to web push notifications and manage its subscription. Before using the Javascript SDK you need to include it in your website as described in the Getting started section.
pushpad('init', projectId, options)
You must always call this function.
// initialize the Pushpad JavaScript SDK with the default settings
pushpad('init', '123');
// if your website already has a service worker:
// 1. make sure that your service worker file is served from the root directory of your website (recommended) or include the HTTP header Service-Worker-Allowed: /
// 2. make sure that your service worker is registered in the root scope and with cache disabled
navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none' });
// 3. then set the serviceWorkerPath to null in init, so that Pushpad doesn't try to register the default service worker
pushpad('init', '123', { serviceWorkerPath: null });
// after init you can use the other commands of the JavaScript SDK...
You can use it to set your projectId
globally. Otherwise you must pass it as an option to the other functions.
// useful if you have multiple projects on the same page
pushpad('init');
pushpad('subscribe', function () {}, { projectId: "123" });
pushpad('subscribe', function () {}, { projectId: "456" });
The same domain can have multiple projects associated to it (think to a project as a "mailing list"). This is also useful to manage multiple environments such as development and production.
pushpad('init', isProductionEnv ? productionProjectId : developmentProjectId);
String projectId
(optional): you can find it in the project settings. If you don't want to set it but you need to pass someoptions
you can usenull
.-
Object options
(optional):String serviceWorkerPath
: the default location is'/service-worker.js'
. If your service worker really needs to be in a different location you can set its path here, however remember that the location of the service worker can affect its behavior and you usually want to put it at the root of your website: don't put the service worker outside the root path unless you know exactly how service workers work. If your web app already registers the service worker, you should set this option tonull
, however in this case make sure that your application callsnavigator.serviceWorker.register
with the options{ scope: '/', updateViaCache: 'none' }
, otherwise your notifications may not work properly.
pushpad('uid', uid, uidSignature)
Associate a user ID to the subscription. It allows to target specific users with web push notifications.
// associate the current browser (its push subscription) to the user 123456
// and authenticate the user with a signature for additional security
pushpad('uid', '123456', '4b9503324d1c97ecfc551dbb377452c85da8ebb9');
// or use this simpler code if you disable the signature verification in project settings:
pushpad('uid', '123456');
If the browser is already subscribed to push notifications, then the uid
is updated immediately. Otherwise the uid
will be associated when a subscription is created:
pushpad('uid', '33', '4b9503324d1c97ecfc551dbb377452c85da8ebb9');
pushpad('subscribe');
// is the same as
pushpad('subscribe', null, { uid: '33', uidSignature: '4b9503324d1c97ecfc551dbb377452c85da8ebb9' });
See subscribe
for a description of the params.
pushpad('tags', replaceTags)
Set the tags for the subscription. It allows to target specific segments with web push notifications.
pushpad('tags', ['tag1', 'tag2']);
If the browser is already subscribed to push notifications, then the tags
are updated immediately and previous tags are removed. Otherwise the tags
will be associated when a subscription is created:
pushpad('tags', ['tag1', 'tag2']);
pushpad('subscribe');
// is the same as
pushpad('subscribe', null, { replaceTags: ['tag1', 'tag2'] });
See subscribe
for a description of the params.
pushpad('status', callback, options)
It lets you know whether the browser is subscribed to your web push notifications and retrieves data about the subscription.
pushpad('status', function (isSubscribed, tags, uid) { console.log(isSubscribed, tags, uid); });
Note that you can also use this function to detect browser support since the callback
is only executed if the browser supports push notifications (however you should prefer the use of the unsupported
function whenever possible).
Function callback(Boolean isSubscribed, String[] tags, String uid)
:isSubscribed
indicates whether the browser is subscribed to push notifications;tags
are the tags associated to that subscription;uid
is the user ID associated to the subscription-
Object options
(optional):String projectId
: overrides the global setting
pushpad('subscribe', callback, options)
Subscribe the browser to web push notifications or update the existing subscription.
pushpad('subscribe', function () { console.log('Subscribed!'); });
// or
pushpad('subscribe', function (isSubscribed) {
if (isSubscribed) {
console.log('Subscribed!');
} else {
console.log('Notifications blocked by the user.');
}
});
// create or update the subscription
pushpad('subscribe', function () {}, {
tags: ['t1', 't2'], // add tags 't1' and 't2'
uid: '33', // keep track of the current user ID
uidSignature: '4b9503324d1c97ecfc551dbb377452c85da8ebb9'
});
// add some tags to the existing subscription
// or create a new subscription with these tags
pushpad('subscribe', function () {}, { tags: ['t1', 't2'] });
// replace all tags for the existing subscription
// or create a new subscription with these tags
pushpad('subscribe', function () {}, { replaceTags: ['t1', 't2'] });
If this is the first time that you call this function for a user, the browser will show him a prompt asking whether he wants to receive the notifications from your website.
You can call subscribe
multiple times if you want, even if the subscription already exists. This can be useful to make sure that new subscriptions are sent to Pushpad or to update the data associated to the existing subscription.
Function callback(isSubscribed)
(optional): if the user has blocked notifications for your websiteisSubscribed
isfalse
and you may want to display a message saying to enable the push notifications from the browser preferences. If the passedcallback
has zero formal parameters, then the callback is only invoked on successful subscription.-
Object options
(optional):String[] tags
: it adds some tags to the subscription. Even if the user is already subscribed you can callsubscribe
multiple times to add new tags to the subscription. Previous tags are not deleted: usereplaceTags
orunsubscribe
for that.String[] replaceTags
: it sets the tags associated to the subscription. Any previous tag is removed.String uid
: an identifier for the current user (e.g. the id of the user in your database) that will be associated to the subscription, in order to find it later and target it with push notifications. Any previousuid
associated to the subscription will be replaced.null
is ignored: useunsubscribe
if you want to remove theuid
.String uidSignature
: the HMAC signature of the user id. You can read more about it in the Targeting users section.String projectId
: overrides the global setting
pushpad('unsubscribe', callback, options)
Unsubscribe the browser from web push notifications or remove data from the subscription.
// remove the subscription to push notifications
pushpad('unsubscribe', function () { console.log('Unsubscribed!'); });
// remove only tag 't1' from the subscription
pushpad('unsubscribe', function () {}, { tags: ['t1'] });
// remove only the user ID from the the subscription
pushpad('unsubscribe', function () {}, { uid: true });
Function callback()
(optional): it is invoked after the subscription is successfully removed-
Object options
(optional):String[] tags
: when this option is passed, instead of deleting the whole subscription,unsubscribe
only removes those tags from the subscriptionBoolean uid
: when this option istrue
, instead of deleting the whole subscription,unsubscribe
only removes the user ID from the subscriptionString projectId
: overrides the global setting
pushpad('unsupported', callback)
It provides a fallback for browsers that don't support web push notifications.
pushpad('unsupported', function () { console.log('Browser unsupported.'); });
Note that when a browser is unsupported the calls to all the other functions are ignored and do not throw any errors.
Function callback()
: a function that is executed when the browser doesn't support push notifications. For example you may want to disable the UI controls for push notifications.
pushpad('widget', options)
The easiest way to collect subscriptions to notifications on your website.
// enable the widget using the settings from the dashboard
pushpad('widget');
// or you can pass some options directly
pushpad('widget', {
prompt: true,
promptDelay: '0 seconds',
promptFrequency: '3 days',
promptTitle: 'Subscribe to notifications',
promptMessage: 'Turn on the notifications for this website to receive the latest news and updates.',
promptIcon: null,
promptButton: 'Subscribe',
promptDismiss: 'No thanks',
promptButtonColor: '#065FD4',
promptPosition: 'left',
bell: true,
bellSize: '50px',
bellBackgroundColor: '#D5333C',
bellPosition: 'right',
bellBadge: '1',
bellAnimation: true,
button: true,
buttonContainer: 'div#pushpad-subscribe',
buttonSubscribe: 'Subscribe',
buttonSubscribed: 'Subscribed',
buttonUnsubscribe: true,
buttonPadding: '1em',
buttonBorderRadius: '9999px',
buttonFontSize: 'medium',
buttonColor: '#FFF',
buttonBackgroundColor: '#D5333C',
buttonSubscribedColor: '#666',
buttonSubscribedBackgroundColor: '#EEE',
deniedTitle: 'Notifications are blocked',
deniedMessage: 'Please open your browser preferences or click the lock 🔒 near the address bar to change your notification preferences.',
margin: '1.5rem',
fontFamily: 'system-ui'
});
The widget offers a simple way to collect subscriptions to web push notifications. In particular this method provides the following UI components:
prompt
: a custom prompt that asks users to subscribe to notificationsbell
: a floating action button that allows users to subscribe to notificationsbutton
: a customizable button that can be placed anywhere on your website to allow users to subscribe or unsubscribe from notifications
The prompt
and bell
are enabled by default, but you can turn them off by setting their option to false
. You can also choose how often the prompt is displayed - to the users that are not subscribed - by changing the promptFrequency
.
If you want to display the prompt
again immediately, on page load, even when you have just closed it, you can simply set promptFrequency: '1 second'
(or something similar).
Alternatively, for development, you can clear all data for the website from browser settings or from developer tools.
The prompt
can be displayed at the bottom of the page (with promptPosition: 'left'
or promptPosition: 'right'
) or at the top of the page (promptPosition: 'top'
).
If you want to display the button
, you can simply add this markup to your page:
<div id="pushpad-subscribe"></div>
You can configure the appearance and behavior of the widget passing the options
directly or using the settings in the dashboard: go to your project, click Settings and then Widget settings. The options
passed directly to the method override the settings in the dashboard. This is useful if you want to use custom values for the options that are not available in the dashboard, or if you need to set the options programmatically depending on the page or context, or if you have a multi-language website.
The prompt
offers many advantages compared with a simple call to subscribe
on page load:
- you can show a custom message to the user before the permission prompt
- you can display the custom prompt again in case the user dismisses it
- you can show the prompt to browsers like Safari that require a user gesture
The widget also leverages local caching to improve performance and reduce the number of HTTP requests. The local cache is cleared when you close the browser.
The widget settings are also cached using the HTTP cache: if you change the settings from the Pushpad dashboard the new settings may take some minutes to appear.
The widget is built upon the other methods of the Javascript SDK and it is fully compatible with them, meaning that you can use the widget and other methods together. In particular you can call uid
and tags
if you want to set them:
pushpad('uid', '33', '4b9503324d1c97ecfc551dbb377452c85da8ebb9');
pushpad('tags', ['tag1', 'tag2']);
pushpad('widget');