Pushpad Logo Pushpad

Pushpad Pro: 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.

Some examples use jQuery, but you can use vanilla Javascript as well. The SDK doesn't use jQuery.

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 just a few lines of code.

pushpad('init', myProjectId);
pushpad('subscribe');

Subscribe users to push notifications after login or signup

A scenario where the previous approach offers a good user experience is when you automatically ask to receive push notifications on a welcome page, after the user has signed up or logged in on your website. In this case it's also useful to add an id of the current user to the subscription so that you can target him later.

pushpad('init', myProjectId);
pushpad('subscribe', function (isSubscribed) {
  // if the user blocks push notifications for your website
  // you may want to display a notice somewhere
  if (!isSubscribed)
    alert('Please enable push notifications from your browser preferences to receive...');
}, { 
  uid: 'myUser1',
  uidSignature: 'mySignature'
});

Unsubscribe a user from web push notifications after logout

When a user logs out from your website you may want to stop sending him notifications on that device.

If you want to stop all notifications:

pushpad('init', myProjectId);
pushpad('unsubscribe');

Another approach is to stop only the confidential notifications (e.g. notifications about the user account), but keep sending general news to that device (e.g. news about blog articles or new features). To do this, instead of removing the whole subscription, just remove the user ID from the subscription:

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

Subscribe button for web push notifications

A minimalist button for subscribing the user to web push notifications.

<button id="pushpad-button">Subscribe</button>
pushpad('init', myProjectId);

$(function () {
  // when the user clicks the button...
  $('#pushpad-button').on('click', function() {
    // try to subscribe the user to push notifications
    pushpad('subscribe', function (isSubscribed) {
      if (isSubscribed) {
        alert("Thanks! You have successfully subscribed to the notifications.");
      } else {
        alert("You have blocked the notifications from browser preferences: please update your browser preferences and then try again. Usually you can change your prefereces by clicking the lock near the address bar.");
      }
    });
  });
});

Subscribe / unsubscribe button for web push notifications

Let's create a simple button to subscribe/unsubscribe the user from push notifications.

<button id="pushpad-button">Subscribe</button>
pushpad('init', myProjectId);

// optionally call 'uid' if the user is logged in to your website
pushpad('uid', 'myUser1', 'mySignature');

$(function () {
  var updateButton = function (isSubscribed) {
    var btn = $('#pushpad-button');
    if (isSubscribed) {
      btn.html('Unsubscribe');
      btn.addClass('subscribed');
    } else {
      btn.html('Subscribe');
      btn.removeClass('subscribed');
    }
  };
  // check whether the user is subscribed to the push notifications and
  // initialize the button status (e.g. display Subscribe or Unsubscribe)
  pushpad('status', updateButton);

  // when the user clicks the button...
  $('#pushpad-button').on('click', function(e) {
    e.preventDefault();

    // if he wants to unsubscribe
    if ($(this).hasClass('subscribed')) {
      pushpad('unsubscribe', function () { 
        updateButton(false);
      });

    // if he wants to subscribe
    } else {
      // try to subscribe the user to push notifications
      pushpad('subscribe', function (isSubscribed) { 
        if (isSubscribed) {
          // success
          updateButton(true);
        } else {
          // oops... the user has denied permission from the browser prompt
          updateButton(false);
          alert('You have blocked notifications from your browser preferences.');
        }
      });
    }
  });

  pushpad('unsupported', function () {
    $('#pushpad-button').prop('disabled', true);
    alert("Your browser doesn't support push notifications.");
  });
});

Notification preferences with checkboxes

Let's see how to build a form which allows the user to select which web push notifications wants to receive on the current browser.

<label>
  <input type="checkbox" class="push-preference" data-tag="topic1">
  Topic1
</label>
<label>
  <input type="checkbox" class="push-preference" data-tag="topic2">
  Topic2
</label>
pushpad('init', myProjectId);

// get some information about the current subscription:
// we use it to initialize the checkboxes
pushpad('status', function (isSubscribed, tags) {

  // for each checkbox
  $('.push-preference').each(function () {
    var element = $(this);
    var tag = element.data('tag');

    // initialize the checkbox to the correct status: checked / unchecked
    if (isSubscribed && tags.indexOf(tag) != -1) {
      element.prop('checked', true);
    } else {
      element.prop('checked', false);
    }

    // listen for events on the checkbox
    element.on('change', function (e) {
      e.preventDefault();

      // when the checkbox is checked you must subscribe to push notifications
      if(element.is(':checked')) {
        // we'll check the checkbox again when we are absolutely sure that 
        // the subscription is successful
        element.prop('checked', false);

        pushpad('subscribe', function (isSubscribed) {
          if (isSubscribed) {
            element.prop('checked', true);
          } else {
            alert('You have blocked the notifications for this website. Please change your browser preferences and try again.');
          }
        }, { tags: [tag] });

      // when the checkbox is unchecked you must unsubscribe from push notifications
      } else {
        pushpad('unsubscribe', function () {
          element.prop('checked', false);
        }, { tags: [tag] });
      }
    });
  });

});

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.

pushpad('init', myProjectId);

// in your backend you should define a method like user.tags 
// which returns all the traits for the current user
// we also use a prefix "user:" as a namespace
var userTags = ['user:young', 'user:likes:music', 'user:lastseen:may2018'];

// update tags on Pushpad:
pushpad('status', function (_, tags) {
  // 1. make sure that the user is subscribed and add tags
  pushpad('subscribe', function () {
    // 2. remove tags (in the "user:" namespace) that are no longer associated to the user
    var trash = tags ? tags.filter(function(tag) {
      return tag.startsWith('user:') && userTags.indexOf(tag) < 0;
    }) : [];
    if (trash.length) pushpad('unsubscribe', function () {}, { tags: trash });
  }, { tags: userTags });
});

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.

<div id="notifications-prompt" style="display: none;">
  <h3>Subscribe To Our Notifications</h3>
  <p>Enable the notifications for this website to receive the latest news and updates from our team.</p>
  <button id="pushpad-button">Subscribe</button>
  <button id="notifications-prompt-dismiss">No, thanks</button>
</div>
pushpad('init', myProjectId);

$(function () {
  // show the custom prompt to users who are not subscribed
  // and don't show the prompt again if the user has already dismissed it during this session
  pushpad('status', function (isSubscribed) {
    if (!isSubscribed && window.sessionStorage.getItem("notifications-prompt") != "dismissed")
      $('#notifications-prompt').show();
  });

  // subscribe the users when they click the "Subscribe" button
  $('#pushpad-button').on('click', function() {
    pushpad('subscribe', function (isSubscribed) {
      if (isSubscribed) {
        $('#notifications-prompt').hide();
      } else {
        alert("You have blocked the notifications from browser preferences: please update your browser preferences and then try again.");
      }
    });
  });

  // close the prompt and remember to not display it again during this session
  $('#notifications-prompt-dismiss').on('click', function () {
    $('#notifications-prompt').hide();
    window.sessionStorage.setItem("notifications-prompt", "dismissed");
  });
});

Ask users to unblock the notifications for your website

If a user blocks your notifications or if he has blocked your notifications in the past, you may want to display a message to that user asking to allow the notifications.

This example differs from the previous one because you try to subscribe the user directly and you show a prompt only to users who have blocked the notifications, while in the previous example you show a custom prompt to all users who are not subscribed.

<div id="notifications-prompt" style="display: none;">
  <p>Enable the notifications for this website to receive the latest news and updates from our team. You can open your browser preferences or click the lock near the address bar to change your notification preferences.</p>
  <button id="notifications-prompt-dismiss">Got it</button>
</div>
pushpad('init', myProjectId);

$(function () {
  pushpad('subscribe', function (isSubscribed) {
    if (!isSubscribed && window.sessionStorage.getItem("notifications-prompt") != "dismissed")
      $('#notifications-prompt').show();
  });

  $('#notifications-prompt-dismiss').on('click', function () {
    $('#notifications-prompt').hide();
    window.sessionStorage.setItem("notifications-prompt", "dismissed");
  });
});

Welcome message

Sometimes it can be useful to detect when a user subscribes to your web push notifications.

If you call pushpad('subscribe') on page load for example, its callback is executed on every page load. If you want to execute something only once, when the subscription is created, then you need to use a code similar to the following example.

pushpad('init', myProjectId);

pushpad('status', function (isSubscribed) {
  // if the user is not subscribed...
  if (!isSubscribed) {
    pushpad('subscribe', function (isSubscribed) {
      // ... and then is subscribed
      if (isSubscribed) {
        // do something (e.g. display a message)
      }
    });
  }
});

You can also use this strategy to send welcome notifications.