78 lines
2.4 KiB
JavaScript
78 lines
2.4 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 registrations = await navigator.serviceWorker.getRegistrations();
|
|
if (!registrations?.length) return false;
|
|
|
|
return await Promise.any(
|
|
registrations.map(async (reg) => !!(await reg.pushManager.getSubscription()))
|
|
).catch(() => false);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function unregisterPush() {
|
|
checkServiceWorkerSupport();
|
|
try {
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
if (!registrations?.length) return;
|
|
|
|
await Promise.all(
|
|
registrations.map(async (reg) => {
|
|
const sub = await reg.pushManager.getSubscription();
|
|
if (sub) await sub.unsubscribe();
|
|
await reg.unregister();
|
|
})
|
|
);
|
|
} catch (err) {
|
|
console.error("Failed to unregister push:", 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)
|
|
}
|
|
} |