69 lines
2.1 KiB
JavaScript
69 lines
2.1 KiB
JavaScript
function checkServiceWorkerSupport() {
|
|
if (!"serviceWorker" in navigator || !"PushManager" in window)
|
|
throw new Error("Your browser does not have Service Worker support")
|
|
}
|
|
|
|
async function unregisterPush() {
|
|
checkServiceWorkerSupport();
|
|
|
|
const registration = await navigator.serviceWorker.getRegistration();
|
|
if (!registration) return;
|
|
|
|
const subscription = await reg.pushManager.getSubscription();
|
|
if (!subscription) return;
|
|
|
|
await subscription.unsubscribe();
|
|
}
|
|
|
|
async function registerPush(publicKey) {
|
|
checkServiceWorkerSupport();
|
|
|
|
const registration = await navigator.serviceWorker.register("/assets/custom/serviceWorker.js");
|
|
console.log("Service Worker registered");
|
|
|
|
let subscription = await registration.pushManager.getSubscription();
|
|
|
|
if (!subscription) {
|
|
const applicationServerKey = urlBase64ToUint8Array(publicKey);
|
|
subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey
|
|
});
|
|
console.log("Push subscription obtained");
|
|
}
|
|
|
|
const response = await fetch(`${window.GLOBAL_ENV.API_ENDPOINT}/v9/users/@me/devices`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Authorization": localStorage.token
|
|
},
|
|
body: JSON.stringify({
|
|
provider: "webpush",
|
|
webpush_subscription: subscription
|
|
})
|
|
});
|
|
|
|
if (response.ok) {
|
|
console.log("Device registered successfully");
|
|
} else {
|
|
const text = await response.text();
|
|
throw new Error("Failed to register: ", text)
|
|
}
|
|
}
|
|
|
|
function urlBase64ToUint8Array(base64String) {
|
|
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
|
|
const base64 = (base64String + padding)
|
|
.replace(/\-/g, "+")
|
|
.replace(/_/g, "/");
|
|
|
|
const rawData = atob(base64);
|
|
const outputArray = new Uint8Array(rawData.length);
|
|
|
|
for (let i = 0; i < rawData.length; i++) {
|
|
outputArray[i] = rawData.charCodeAt(i);
|
|
}
|
|
|
|
return outputArray;
|
|
} |