| 1 |
// eslint-disable-next-line import/no-unresolved |
| 2 |
import { registerSW as viteRegisterSW } from "virtual:pwa-register"; |
| 3 |
|
| 4 |
// fetch new sw every hour, i.e. update app every hour while running |
| 5 |
const intervalMS = 60 * 60 * 1000; |
| 6 |
|
| 7 |
// https://vite-pwa-org.netlify.app/guide/periodic-sw-updates.html |
| 8 |
const registerSW = () => { |
| 9 |
console.log("[ServiceWorker] Registering service worker"); |
| 10 |
if (!("serviceWorker" in navigator)) { |
| 11 |
console.warn("[ServiceWorker] Service workers not supported"); |
| 12 |
return; |
| 13 |
} |
| 14 |
|
| 15 |
viteRegisterSW({ |
| 16 |
onRegisteredSW(swUrl, registration) { |
| 17 |
console.log("[ServiceWorker] Registered:", { swUrl, registration }); |
| 18 |
|
| 19 |
if (!registration) { |
| 20 |
console.warn("[ServiceWorker] No registration returned"); |
| 21 |
return; |
| 22 |
} |
| 23 |
|
| 24 |
setInterval(async () => { |
| 25 |
if (registration.installing || navigator?.onLine === false) return; |
| 26 |
|
| 27 |
const resp = await fetch(swUrl, { |
| 28 |
cache: "no-store", |
| 29 |
headers: { |
| 30 |
cache: "no-store", |
| 31 |
"cache-control": "no-cache", |
| 32 |
}, |
| 33 |
}); |
| 34 |
|
| 35 |
if (resp?.status === 200) { |
| 36 |
console.log("[ServiceWorker] Updating service worker"); |
| 37 |
await registration.update(); |
| 38 |
} |
| 39 |
}, intervalMS); |
| 40 |
}, |
| 41 |
onRegisterError(error) { |
| 42 |
console.error("[ServiceWorker] Registration error:", error); |
| 43 |
}, |
| 44 |
}); |
| 45 |
}; |
| 46 |
|
| 47 |
export default registerSW; |