20 lines
924 B
TypeScript
20 lines
924 B
TypeScript
export async function ensureServiceWorker(): Promise<ServiceWorkerRegistration> {
|
|
const registration = await navigator.serviceWorker.register("/sw.js", { updateViaCache: "none" });
|
|
// ready can otherwise remain pending forever after an install failure.
|
|
return new Promise((resolve, reject) => {
|
|
const timeout = setTimeout(() => reject(new Error("The notification worker did not become ready. Reload and try again.")), 15000);
|
|
void navigator.serviceWorker.ready.then(ready => { clearTimeout(timeout); resolve(ready); }, () => {
|
|
clearTimeout(timeout); reject(new Error("The notification worker is unavailable."));
|
|
});
|
|
void registration.update().catch(() => undefined);
|
|
});
|
|
}
|
|
|
|
export function registerServiceWorker() {
|
|
if (!import.meta.env.PROD || !("serviceWorker" in navigator)) return;
|
|
|
|
window.addEventListener("load", () => {
|
|
void ensureServiceWorker().catch(() => undefined);
|
|
});
|
|
}
|