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 some browsers may block 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.");
      }
    });
  });
});

Asking users to subscribe to notifications by displaying a message

You can easily detect users that are not subscribed to your notifications and display a custom message.

<div id="subscribe-message" style="display: none;">
  Please enable the notifications for this website:
  <button id="notifications-button">Subscribe</button>
</div>
document.addEventListener('DOMContentLoaded', function () {
  // is the user subscribed to notifications?
  pushpad('status', function(isSubscribed) {
    // if the user is not subscribed, display the message
    if (!isSubscribed) document.querySelector('#subscribe-message').style.display = 'block';
  });
});

The message can also contain a subscribe button.

This code is perfect if you plan to use it on a specific page, while, if you include it on all the pages of your website you must cache the status response in some way, for example saving the current status in sessionStorage, in order to avoid too many requests to the API. Alternatively you can use the widget, which already includes all the performance optimizations.

Subscription to notifications for a specific topic

This is useful if you want to allow your website visitors to subscribe or unsubscribe from a specific topic using a button.

<button id="notifications-button" data-topic="mytopic" data-action="subscribe">Subscribe</button>
document.addEventListener('DOMContentLoaded', function () {
  var button = document.getElementById('notifications-button');
  var topic = button.dataset.topic;

  var setButtonStatus = function (isSubscribed) {
    // if you are subscribed to the topic
    // you see that you are already subscribed and you can unsubscribe
    if (isSubscribed) {
      button.innerText = 'Subscribed';
      button.dataset.action = 'unsubscribe';

    // if you are not subsribed to the topic
    // you see a subscribe button
    } else {
      button.innerText = 'Subscribe';
      button.dataset.action = 'subscribe';
    }
  };

  // check if the user is subscribed to the specific topic
  // and initialize the button with the correct status
  pushpad('status', function (isSubscribed, tags) {
    setButtonStatus(isSubscribed && tags.indexOf(topic) != -1);
  });

  // when the user clicks the button...
  button.addEventListener('click', function() {
    // subscribe
    if (button.dataset.action == 'subscribe') {
      pushpad('subscribe', function (isSubscribed) {
        if (isSubscribed) {
          setButtonStatus(true);
        } else {
          alert("You have blocked the notifications from browser preferences.");
        }
      }, { tags: [topic] });

    // unsubscribe
    } else {
      pushpad('unsubscribe', function () {
        setButtonStatus(false);
      }, { tags: [topic] });
    }
  });
});

The advantage of this approach is that the user does not need to be logged in on your website. If your users are registered, then you can store the user preferences in your own database and then sync the data with Pushpad, thus ensuring more durability of user preferences and consistency across multiple user devices.

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.

Abandoned cart notifications

Ecommerce websites may want to send notifications to users that add some items to the cart, but don't complete the purchase.

When a user adds an item to the cart, or when the cart page is displayed, add a tag to the subscription:

pushpad('subscribe', function () {}, { tags: ['pending_cart'] });

Then, when the user completes the purchase, or the cart is empty, remove the tag:

pushpad('unsubscribe', function () {}, { tags: ['pending_cart'] });

Finally you can easily target users that have a pending purchase using the tag pending_cart. You can also use the libraries or Zapier to define a daily job that automatically sends a notification to all devices that have the tag pending_cart. For example, if you use the PHP library, you can run a cron job with the following code:

$notification = new Pushpad\Notification(array(
  'body' => 'You left some items in your cart.',
));
$notification->broadcast(['tags' => ['pending_cart']]);

If you prefer to send only a few notifications, and then stop after some days, the strategy is very similar: you can simply include the current date inside the tag (e.g. pending_cart@2019-06-25) and then, inside the cron job, send the notifications to the tags that include a recent date (e.g. yesterday, the day before yesterday).