Skip to content
This repository has been archived by the owner on Sep 4, 2020. It is now read-only.

Commit

Permalink
Vapid Support (#1675)
Browse files Browse the repository at this point in the history
* Added VAPID key support

* Issue #1140: Fix some VAPID issues on browser
  • Loading branch information
macdonst authored Apr 11, 2017
1 parent 97d618f commit 384b60b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Attribute | Type | Default | Description
Attribute | Type | Default | Description
--------- | ---- | ------- | -----------
`browser.pushServiceURL` | `string` | `http://push.api.phonegap.com/v1/push` | Optional. URL for the push server you want to use.
`browser.applicationServerKey` | `string` | `` | Optional. Your GCM API key if you are using VAPID keys.

#### iOS

Expand Down
2 changes: 1 addition & 1 deletion src/browser/manifest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"name": "Push Demo",
"gcm_sender_id": "85075801930"
"gcm_sender_id": "996231231186"
}
31 changes: 30 additions & 1 deletion www/browser/push.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ var PushNotification = function(options) {
// store the options to this object instance
this.options = options;

// subscription options
var subOptions = {userVisibleOnly: true};
if (this.options.browser.applicationServerKey) {
subOptions.applicationServerKey = urlBase64ToUint8Array(this.options.browser.applicationServerKey);
}

// triggered on registration and notification
var that = this;

Expand All @@ -50,7 +56,7 @@ var PushNotification = function(options) {
})
.then(function(reg) {
serviceWorker = reg;
reg.pushManager.subscribe({userVisibleOnly: true}).then(function(sub) {
reg.pushManager.subscribe(subOptions).then(function(sub) {
subscription = sub;
result = { 'registrationId': sub.endpoint.substring(sub.endpoint.lastIndexOf('/') + 1) };
that.emit('registration', result);
Expand Down Expand Up @@ -322,6 +328,29 @@ PushNotification.prototype.finish = function(successCallback, errorCallback, id)
* Push Notification Plugin.
*/

/**
* Converts the server key to an Uint8Array
*
* @param base64String
*
* @returns {Uint8Array}
*/
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}


module.exports = {
/**
* Register for Push Notifications.
Expand Down

0 comments on commit 384b60b

Please sign in to comment.