Web Push SDK 3.0

Unified Pushwoosh Web SDK: Easy way to send Safari, Chrome and Firefox Browser Pushes

Supports Safari, Chrome, Firefox

Prerequisites

To proceed with the integration of Web Push SDK to your HTTPS website, you should do the following:

  1. Locate your Pushwoosh Application Code.
  2. Chrome and Firefox: locate your Google Project Number/Sender ID.
  3. Safari: locate your Website Push ID.
  4. 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 Incognito mode.

Integration

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.

<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, debug
    applicationCode: 'XXXXX-XXXXX', // you application code from Pushwoosh Control Panel
    safariWebsitePushID: 'web.com.example.domain', //  unique reverse-domain string, obtained in you Apple Developer Portal
    defaultNotificationTitle: 'Pushwoosh', // sets a default title for push notifications
    defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png', // URL to custom custom notification image
    autoSubscribe: false, // or true. If true, promts a user to subscribe for pushes upon SDK initialization
  	subscribeWidget: {
    	enabled: true
    }
    userId: 'userId', // optional, set custom user ID
    tags: {
        'Name': 'John Smith'   	// optional, set custom Tags
    }										
}]);
</script>

Basically, there are two ways you can prompt a user to subscribe for pushes:

  1. Automatically upon the SDK initialization by setting the autoSubscribe parameter to true
  2. Manually, when you set the autoSubscribe parameter to false and call the Pushwoosh.subscribe() method by yourself at any convenient moment.

Registering service worker in a different scope

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:

  1. 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.
  2. Modify the configuration (step 4.3) by adding a parameter serviceWorkerUrl: “/push-notifications” where /push-notifications is the name of the subdirectory with manifest.json and pushwoosh-service-worker.js.
  3. 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!
  4. Add the button that registers user for pushes! Use this guide to implement the subscription button.
    Alternatively, you can use auto subscription using autoSubscribe: true parameter of Web SDK initializer.
  5. Use the Event listener onPermissionGranted (http://docs.pushwoosh.com/docs/web-push-sdk-30#section-permission-tracking-listeners) in order to redirect user back to the main page when he succeeded with the subscription.

Event Listeners

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.

// Executed after successful SDK initialization. 

Pushwoosh.push(['onReady', function(api) {
    console.log('Pushwoosh ready');
}]);
Pushwoosh.push(function(api) {
  console.log('Pushwoosh ready');
});
// Executed after a user agrees to receive push notifications. 

Pushwoosh.push(['onSubscribe', function(api) {
    console.log('Event: onSubscribe triggered');
}]);
//  Executed after a device is unregistered from notifications.

Pushwoosh.push(['onUnsubscribe', function(api) {
    console.log('Event: onUnsubscribe triggered');
}]);

permission tracking listeners

// 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');
}]);
// Executed during the SDK initialization if a user blocks push notifications.

Pushwoosh.push(['onPermissionDenied', function(api) {
    console.log('Event: onPermissionDenied triggered');
}]);
// Executed during the SDK initialization if a user allows push notifications.

Pushwoosh.push(['onPermissionGranted', function(api) {
    console.log('Event: onPermissionGranted triggered');
}]);

Notification tracking listeners

Callbacks for the listeners below have two parameters:

  1. An API object
  2. Push notification payload
// Executed when a push notification is displayed.

Pushwoosh.push(['onPushDelivery', function(api, payload) {
    console.log('Event: onPushDelivery triggered', payload);
}]);
var 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'
  }
};
// Executed when a user clicks on notification.

Pushwoosh.push(['onNotificationClick', function(api, payload) {
    console.log('Event: onNotificationClick triggered', payload);
}]);
var payload = {
  url: 'https://yoursite.com/some/path',
  messageHash: '2m'
};
// Executed when a push notification is closed.

Pushwoosh.push(['onNotificationClose', function(api, payload) {
    console.log('Event: onNotificationClose triggered', payload);
}]);
var payload = {
  url: 'https://yoursite.com/some/path',
  messageHash: '2m'
};

API

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 user
  api.setTags({
    'Tag Name 1' => 'value1',
    'Tag Name 2' => 'value2'
  });
 
  // Get tags for a user from server
  api.getTags();
   
  // Register user ID
  api.registerUser('myUserID');
  
  // Post an Event
  api.postEvent('myEventName', {attributeName: 'attributeValue'});

 	//Unregister from notifications
  api.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);
    });
});

Public Methods

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.
  1. 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()

  1. /unregisterDevice method is executed.
  2. 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;
});

Progressive Web App support

The latest version of Web Push SDK 3.0 supports PWA out of the box. There is on thing to keep in mind if you would like to use our WebSDK with PWA - service workers initialization behaviour.

In case you need to initialize it in one scope with PWA's service worker you don't need to register it separately, just add it into the importScripts within pushwoosh-service-worker.js:

importScripts('https://cdn.pushwoosh.com/webpush/v3/pushwoosh-service-worker.js', 'PWA-service-worker.js') 
// Where PWA-service-worker.js as a service worker of your Progressive Web App 

If PWA and WebSDK scopes does not intersect with each other, then everything will work without additional changes.

Install from npm

Install Web Push SDK as a node module and save it as a dependency in your package.json:

npm install web-push-notifications --save
var Pushwoosh = require('web-push-notifications').Pushwoosh;
var pwInstance = new Pushwoosh();
pwInstance.push(['init', {
    logLevel: 'info', // or debug
    applicationCode: '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'
    }
}]);
import {Pushwoosh} from 'web-push-notifications';
const pwInstance = new Pushwoosh();
pwInstance.push(['init', {
    logLevel: 'info', // or debug
    applicationCode: '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'
    }
}]);

Web Push SDK 3.0

Unified Pushwoosh Web SDK: Easy way to send Safari, Chrome and Firefox Browser Pushes