rastrillo / pwa Public

Clone
git clone https://amadan.net/rastrillo/pwa

Plain git — no account needed to clone.

Download

Download this file

1// No reload or permission prompt is implicit: the app knows about unsaved work
2// and whether the person actually asked to enable notifications.
3export async function register({ url = "/sw.js", scope, onUpdate = () => {} } = {}) {
4 if (!globalThis.navigator?.serviceWorker) return null;
5 const registration = await navigator.serviceWorker.register(url, {
6 ...(scope ? { scope } : {}),
7 updateViaCache: "none",
8 });
9 const seen = new WeakSet();
10 const notify = () => {
11 const worker = registration.waiting;
12 if (worker && !seen.has(worker)) {
13 seen.add(worker);
14 onUpdate(registration);
15 }
16 };
17 const watch = () => {
18 registration.installing?.addEventListener("statechange", notify);
19 notify();
20 };
21 registration.addEventListener("updatefound", watch);
22 watch();
23 return registration;
24}
25
26// Activation affects the registration shared by all tabs. Call only after the
27// app has resolved unsaved work across those tabs; this helper never reloads.
28export function activateUpdate(registration) {
29 if (!registration?.waiting) return false;
30 registration.waiting.postMessage({ type: "rastrillo:pwa:activate" });
31 return true;
32}
33