app/webpacker/src/javascript/serviceworker-companion.js.erb
function configureWebPush(subscription) {
$.post({ url: '/configure_webpush', data: { subscription: subscription.toJSON() } });
}
var swRegistration = null;
function subscribeServiceWorker(serviceWorkerRegistration) {
swRegistration = serviceWorkerRegistration
swRegistration.pushManager.getSubscription().then(function(subscription) {
if (!subscription) {
var key = new Uint8Array(<%= Base64.urlsafe_decode64(ReviewitConfig.webpush_public_key).bytes %>)
swRegistration.pushManager.subscribe({ userVisibleOnly: true,
applicationServerKey: key }).then(configureWebPush);
} else {
configureWebPush(subscription);
}
swRegistration = null;
});
}
function receiveMessageFromServiceWorker(event) {
console.log("To be implemented soon! :-)");
console.log(event.data);
}
function registerWebPushNotifications() {
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js', { scope: '/' }).then(subscribeServiceWorker);
navigator.serviceWorker.addEventListener('message', receiveMessageFromServiceWorker);
if (Notification.permission !== 'denied' && Notification.permission !== 'granted') {
Notification.requestPermission();
}
console.log('Service worker registered!');
} else {
console.log('Service workers not supported by this browser.');
}
}