95 lines
2.3 KiB
JavaScript
95 lines
2.3 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();
|
|
for (const reg of registrations) {
|
|
if (!reg.pushManager) continue;
|
|
|
|
const sub = await reg.pushManager.getSubscription();
|
|
if (sub) return true;
|
|
}
|
|
|
|
const reg = await navigator.serviceWorker.getRegistration();
|
|
if (!reg || !reg.pushManager) return false;
|
|
|
|
const sub = await reg.pushManager.getSubscription();
|
|
return !!sub;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function unregisterPush() {
|
|
checkServiceWorkerSupport();
|
|
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
if (!registrations || registrations.length === 0) return;
|
|
|
|
for (const reg of registrations) {
|
|
if (!reg.pushManager) continue;
|
|
|
|
const sub = await reg.pushManager.getSubscription();
|
|
if (sub) {
|
|
await sub.unsubscribe();
|
|
}
|
|
|
|
if (!window.IS_IOS) {
|
|
await reg.unregister();
|
|
}
|
|
}
|
|
}
|
|
|
|
async function registerPush(publicKey) {
|
|
checkServiceWorkerSupport();
|
|
|
|
if (window.IS_IOS && !window.IS_STANDALONE) {
|
|
throw new Error(
|
|
"On iOS, notifications require adding this site to the Home Screen"
|
|
);
|
|
}
|
|
|
|
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"
|
|
);
|
|
|
|
let subscription = await registration.pushManager.getSubscription();
|
|
|
|
if (!subscription) {
|
|
const applicationServerKey = urlBase64ToUint8Array(publicKey);
|
|
subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey
|
|
});
|
|
}
|
|
|
|
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",
|
|
subscription
|
|
})
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
throw new Error(text);
|
|
}
|
|
} |