Pushpad

Javascript SDK examples

The Javascript SDK can be used to subscribe a browser to web push notifications and to manage the data associated to that subscription. The following examples show some common uses of the Javascript SDK.

Before using the examples, make sure to install Pushpad and remember to initialize the Javascript SDK:

pushpad('init', myProjectId);

Subscription to web push notifications on page load

Asking visitors to receive notifications as soon as they enter the website is quite common practice. Even if this solution doesn't always offer the best user experience and you should prefer other methods, this is definitely a widespread use case that can be implemented with a single line of code:

pushpad('subscribe');

The above code works great if you call it only on a specific page of your website (e.g. on your homepage or after login). If you use it on many pages, it will create too many HTTP requests. In case you want to include the code on multiple pages of your website you must use caching to trigger the subscription process at most once per session:

if (window.sessionStorage.getItem('notification-status') != 'subscribed')
  pushpad('subscribe', function () { window.sessionStorage.setItem('notification-status', 'subscribed'); });

If the user blocks the notifications, you cannot display the browser prompt again. Also note that the latest version of Safari desktop blocks the notification prompt on page load. In order to avoid these problems you can use a button or a custom prompt as described in the following examples.

User authentication after login

After the user has signed up or logged in on your website you can add the id of the current user to the subscription so that you can target him later. Add the following code to the page where the user is redirected to after login:

pushpad('uid', 'myUser1', 'mySignature');

You can learn more in the docs.

Unsubscribe a user from web push notifications

If you want to unsubscribe the current device from all the notifications use this code:

pushpad('unsubscribe');

Alternatively, when the user logs out, you can decide to stop only the confidential notifications about the user account, but keep sending general news. To do this, instead of removing the whole subscription, just remove the user ID from the subscription:

pushpad('unsubscribe', function () {}, { uid: true });

Subscribe button for web push notifications

Let's see how to create a button to subscribe the users to web push notifications.

The easiest solution is to use the widget:

<div id="pushpad-subscribe"></div>
pushpad('widget');

There are also many options to change the appearance and behavior of the widget.

If you prefer, you can also build a button from scratch using the Javascript SDK:

<button id="notifications-button">Subscribe</button>
document.addEventListener('DOMContentLoaded', function () {
  // when the user clicks the button...
  document.querySelector('#notifications-button').addEventListener('click', function() {
    // try to subscribe the user to push notifications
    pushpad('subscribe', function (isSubscribed) {
      if (isSubscribed) {
        alert("Thanks! You have successfully subscribed to notifications.");
      } else {
        alert("You have blocked the notifications from browser preferences.");
      }
    });
  });
});

Notification preferences with checkboxes

You can create a form to allow users to choose the notifications that they want to receive on the current browser.

First create a subscribe button to subscribe or unsubscribe users from notifications.

Then you can add some checkboxes to allow users to select their preferences:

<label>
  <input type="checkbox" name="tags[]" value="topic1" class="notification-preferences">
  Topic1
</label>
<label>
  <input type="checkbox" name="tags[]" value="topic2" class="notification-preferences">
  Topic2
</label>
document.addEventListener('DOMContentLoaded', function () {
  // load preferences from local storage
  var tags = JSON.parse(window.localStorage.getItem('notification-preferences')) || [];

  // sync data with Pushpad
  pushpad('tags', tags);

  var checkboxes = document.querySelectorAll('.notification-preferences');
  checkboxes.forEach(function(checkbox) {
    // initialize the checkboxes with the correct state
    if (tags.indexOf(checkbox.value) !== -1)
      checkbox.checked = true;

    // save new preferences when a checkbox is changed
    checkbox.addEventListener('change', function (event) {
      if (event.target.checked) {
        // add tag when the checkbox is checked
        tags.push(event.target.value);
      } else {
        // remove tag when the checkbox is unchecked
        tags = tags.filter(tag => tag !== event.target.value);
      }
      window.localStorage.setItem('notification-preferences', JSON.stringify(tags));
      
      // sync data with Pushpad
      pushpad('tags', tags);
    });
  });
});

Basically we use localStorage to save the user preferences and then we sync that information with Pushpad.

If the users are logged in there are some alternatives:

Keep track of user properties with tags

Tags can be used both for notification preferences and for describing the traits of a user. If your web application has a user model, you may want to sync that data with Pushpad, so that you can easily create and target segments from the Pushpad dashboard or using the API.

// you should gather all the tags in one place
// in your backend you can define a method like user.tags which returns all the traits for the current user
// you can also include tags that you get from API calls, browser preferences, local storage, etc.
var userTags = ['young', 'likes:music', 'lastseen:2019-01', 'lang:en'];

// then update all the tags on Pushpad with a single call
pushpad('tags', userTags);
// or
pushpad('subscribe', function () {}, { replaceTags: userTags });

Usually it is easier to track the user in your database or using cookies and then update all tags every once in a while, instead of trying to update the subscription each time that something happens. You can define a helper function like getUserTags() which returns all tags for the user, including the tags that you get from server and those that you get from local storage. This also allows you to compute user traits with all the data available: for example, instead of adding a tag when a user completes a purchase, you can compute better tags using the full purchase history available in the database.

Before adopting this strategy for targeting, please consider that there are some alternatives: for example, if you send the notifications automatically using the API, then you can query your database to find a group of users and then target the user IDs directly without using tags.

Also note that this strategy only ensures eventual consistency of tags: you need to wait that a browser visits your website in order to update tags. If you don't want to wait, you can update tags from your backend using the Subscriptions API.

Custom prompt for web push notifications

The most direct way to ask users to subscribe is to show the browser native prompt, as described in the previous example. However, if you prefer, you can show a custom message and ask nicely to the user if he wants to subscribe before displaying the permission prompt. This approach is recommended by some usability guides and it also avoids that the user permanently blocks the notifications from browser preferences: unlike the browser prompt, you can display your custom prompt multiple times.

pushpad('widget');

There are also many options to customize the prompt.