Skip to content

Instantly share code, notes, and snippets.

@martijndwars
Created August 30, 2016 21:43
Show Gist options
  • Save martijndwars/c05c531e33e9b39452425b131c482c8f to your computer and use it in GitHub Desktop.
Save martijndwars/c05c531e33e9b39452425b131c482c8f to your computer and use it in GitHub Desktop.
push.js
$(function () {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(initialiseState);
} else {
console.warn('Service workers are not supported in this browser.');
}
});
function initialiseState() {
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
console.warn('Notifications aren\'t supported.');
return;
}
if (Notification.permission === 'denied') {
console.warn('The user has blocked notifications.');
return;
}
if (!('PushManager' in window)) {
console.warn('Push messaging isn\'t supported.');
return;
}
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.getSubscription().then(function (subscription) {
if (!subscription) {
subscribe();
return;
}
// Keep your server in sync with the latest subscriptionId
sendSubscriptionToServer(subscription);
})
.catch(function(err) {
console.warn('Error during getSubscription()', err);
});
});
}
function subscribe() {
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true}).then(function (subscription) {
return sendSubscriptionToServer(subscription);
})
.catch(function (e) {
if (Notification.permission === 'denied') {
console.warn('Permission for Notifications was denied');
} else {
console.error('Unable to subscribe to push.', e);
}
});
});
}
function sendSubscriptionToServer(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
var auth = subscription.getKey ? subscription.getKey('auth') : '';
return fetch('/profile/subscription', {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="_csrf"]').attr('content')
},
method: 'POST',
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : '',
auth: auth ? btoa(String.fromCharCode.apply(null, new Uint8Array(auth))) : ''
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment