PWA_SCRIPT

tcmts.cli.web.PWA_SCRIPT · #kx4pchfn · term · runs anywhere

What a PWA's page runs first: it registers the app's service worker (sw.js, under the app's base), and says when a new version has taken over (tcm:update on window, and useAppUpdate in the react library), for the next load. An installed app can stay open for days, so it looks for one whenever it's back on screen (once a minute at most).

export const PWA_SCRIPT = `<script>
if ("serviceWorker" in navigator) {
  const base = globalThis.__TCM_BASE__ ?? "";
  // opened by a service worker already: one that takes over now is a new version
  const had = !!navigator.serviceWorker.controller;
  navigator.serviceWorker.addEventListener("controllerchange", () => {
    if (!had || globalThis.__tcmUpdate) return;
    globalThis.__tcmUpdate = true;
    dispatchEvent(new Event("tcm:update"));
  });
  addEventListener("load", () => {
    navigator.serviceWorker.register(base + "/sw.js", { scope: base + "/", updateViaCache: "none" }).then((r) => {
      let checked = Date.now();
      document.addEventListener("visibilitychange", () => {
        if (document.visibilityState !== "visible" || Date.now() - checked < 60000) return;
        checked = Date.now();
        r.update().catch(() => {});
      });
    }, (e) => console.warn("tcm: the app's service worker didn't register:", e));
  });
}
</script>`

used by