diff --git a/frontend/src/lib/serviceWorker.ts b/frontend/src/lib/serviceWorker.ts index d82ecf65..517ab4c2 100644 --- a/frontend/src/lib/serviceWorker.ts +++ b/frontend/src/lib/serviceWorker.ts @@ -30,37 +30,47 @@ export function offServiceWorkerUpdate(): void { updateCallback = null; } +const UPDATE_CHECK_INTERVAL_MS = 60 * 1000; + export function registerServiceWorker(): void { if (!("serviceWorker" in navigator)) return; + const hadController = !!navigator.serviceWorker.controller; + navigator.serviceWorker.addEventListener("message", (event) => { if (event.data?.type === "SW_UPDATED") { notifyUpdate(); } }); - navigator.serviceWorker.ready.then((registration) => { - if (registration.waiting) { - notifyUpdate(); - } - }); - navigator.serviceWorker .register("/sw.js", { scope: "/" }) .then((registration) => { + if (registration.waiting && hadController) { + notifyUpdate(); + } + registration.addEventListener("updatefound", () => { const installing = registration.installing; if (!installing) return; installing.addEventListener("statechange", () => { - if (installing.state === "installed" && navigator.serviceWorker.controller) { + if (installing.state === "installed" && hadController) { notifyUpdate(); } }); }); - setInterval(() => { + const checkForUpdate = () => { registration.update().catch(() => {}); - }, 60 * 60 * 1000); + }; + + const onVisibilityChange = () => { + if (document.visibilityState === "visible") checkForUpdate(); + }; + + document.addEventListener("visibilitychange", onVisibilityChange); + window.addEventListener("focus", checkForUpdate); + setInterval(checkForUpdate, UPDATE_CHECK_INTERVAL_MS); }) .catch(() => {}); }