91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
var applicationServerPublicKey = {{ pwa_vapid_public_key|as_json|safe }};
|
|
var COMBO_PWA_USER_SUBSCRIPTION = false;
|
|
|
|
function urlB64ToUint8Array(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;
|
|
}
|
|
|
|
if ('serviceWorker' in navigator) {
|
|
navigator.serviceWorker.register('/service-worker.js', {scope: '/'}).then(function(registration) {
|
|
// Registration was successful
|
|
console.log('ServiceWorker registration successful with scope: ', registration.scope);
|
|
swRegistration = registration;
|
|
combo_pwa_initialize();
|
|
}).catch(function(err) {
|
|
// registration failed :(
|
|
console.log('ServiceWorker registration failed: ', err);
|
|
});
|
|
}
|
|
|
|
function combo_pwa_initialize() {
|
|
if (applicationServerPublicKey !== null) {
|
|
swRegistration.pushManager.getSubscription()
|
|
.then(function(subscription) {
|
|
if (subscription !== null) {
|
|
COMBO_PWA_USER_SUBSCRIPTION = true;
|
|
} else {
|
|
COMBO_PWA_USER_SUBSCRIPTION = false;
|
|
}
|
|
$(document).trigger('combo:pwa-user-info');
|
|
});
|
|
}
|
|
}
|
|
|
|
function combo_pwa_subscribe_user() {
|
|
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
|
|
swRegistration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: applicationServerKey
|
|
})
|
|
.then(function(subscription) {
|
|
console.log('User is subscribed.');
|
|
COMBO_PWA_USER_SUBSCRIPTION = true;
|
|
$(document).trigger('combo:pwa-user-info');
|
|
combo_pwa_update_subscription_on_server(subscription);
|
|
})
|
|
.catch(function(err) {
|
|
console.log('Failed to subscribe the user: ', err);
|
|
});
|
|
}
|
|
|
|
function combo_pwa_unsubscribe_user() {
|
|
swRegistration.pushManager.getSubscription()
|
|
.then(function(subscription) {
|
|
if (subscription) {
|
|
return subscription.unsubscribe();
|
|
}
|
|
})
|
|
.catch(function(error) {
|
|
console.log('Error unsubscribing', error);
|
|
})
|
|
.then(function() {
|
|
combo_pwa_update_subscription_on_server(null);
|
|
console.log('User is unsubscribed.');
|
|
COMBO_PWA_USER_SUBSCRIPTION = false;
|
|
$(document).trigger('combo:pwa-user-info');
|
|
});
|
|
}
|
|
|
|
function combo_pwa_update_subscription_on_server(subscription) {
|
|
$.ajax({
|
|
url: '{% url "pwa-subscribe-push" %}',
|
|
data: JSON.stringify(subscription),
|
|
contentType: 'application/json; charset=utf-8',
|
|
type: 'POST',
|
|
dataType: 'json',
|
|
success: function(response) {
|
|
}
|
|
});
|
|
}
|