All checks were successful
Deploy to Netlify / Deploy to Netlify (push) Successful in 1m42s
47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { subscribe, unsubscribe } from "./api";
|
|
|
|
export const STORAGE_KEY = "notification_enabled";
|
|
|
|
export async function registerNotification() {
|
|
const permission = await Notification.requestPermission();
|
|
if (permission !== "granted") {
|
|
return {
|
|
error: "E_PERMISSION_DENIED",
|
|
};
|
|
}
|
|
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
|
|
return {
|
|
error: "E_UNSUPPORTED",
|
|
};
|
|
}
|
|
const registration = await navigator.serviceWorker.ready;
|
|
try {
|
|
const subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: import.meta.env.VITE_PUBLIC_VAPID_KEY,
|
|
});
|
|
const data = await subscribe(subscription);
|
|
// Store to local storage
|
|
localStorage.setItem(STORAGE_KEY, data.id?.toString());
|
|
return subscription;
|
|
} catch (err) {
|
|
return {
|
|
error: "Erreur : " + err,
|
|
};
|
|
}
|
|
}
|
|
|
|
export function isNotificationEnabled() {
|
|
return !!localStorage.getItem(STORAGE_KEY);
|
|
}
|
|
|
|
export async function unregisterNotification() {
|
|
const subscriptionId = localStorage.getItem(STORAGE_KEY);
|
|
if (!subscriptionId) {
|
|
return {
|
|
error: "E_NOT_REGISTERED",
|
|
};
|
|
}
|
|
await unsubscribe(subscriptionId);
|
|
localStorage.removeItem(STORAGE_KEY);
|
|
}
|