Skip to content

Instantly share code, notes, and snippets.

@charisTheo
Last active January 6, 2020 17:08
Show Gist options
  • Select an option

  • Save charisTheo/6efe941fccd87c8317853e7e525a62e1 to your computer and use it in GitHub Desktop.

Select an option

Save charisTheo/6efe941fccd87c8317853e7e525a62e1 to your computer and use it in GitHub Desktop.
Register Service Worker on the front-end and request Push Permission
if ('serviceWorker' in navigator) { // || 'ServiceWorker' in window
sw();
}
function sw() {
const registration = navigator.serviceWorker.register('/sw.js', {scope: '/'})
.then(function(_registration) {
console.log('Registration succeeded. Scope is ' + _registration.scope);
// request push notification permission only when user clicks the notification button as a good practise
$('#notifications-button').on("click", function() {
// check permissions if notifications icon is clicked
_registration.pushManager.permissionState({userVisibleOnly: true}).then(permission => {
// Possible values are 'prompt', 'denied', or 'granted'
if (permission === "prompt") {
// request permission only when user has not either denied or accepted notifications
requestPushPermission(_registration);
}
}).catch(() => {
// error
});
});
}).catch(function(error) {
console.log('Registration failed with ' + error);
});
}
function requestPushPermission(registration) {
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY) // PUBLIC_VAPID_KEY is created by a push manager on the back-end
}).then(function(subscription) {
fetch('/subscribe', { // custom route for handling and saving the push subscription of the user
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'content-type': 'application/json'
}
});
console.log("user subscribed");
});
}
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 (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment