This repository has been archived on 2026-02-28. You can view files and clone it, but cannot push or open issues or pull requests.
2025-12-21 16:14:34 +02:00

76 lines
2.2 KiB
JavaScript

function checkServiceWorkerSupport() {
if (!("serviceWorker" in navigator) || !("PushManager" in window))
throw new Error("Your browser does not have Service Worker support")
}
async function isPushRegistered() {
checkServiceWorkerSupport();
try {
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
return !!sub;
} catch {
return false;
}
}
async function unregisterPush() {
checkServiceWorkerSupport();
try {
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
if (sub) {
await sub.unsubscribe();
}
if (!window.isIOS()) {
await reg.unregister();
}
} catch (err) {
alert("Failed to unregister push");
console.error(err);
}
}
async function registerPush(publicKey) {
checkServiceWorkerSupport();
const permission = await Notification.requestPermission();
if (permission !== "granted") {
throw new Error("Notification permission not granted");
}
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": window.AUTH_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)
}
}