From 0cca2caa2e372312e4c6157e216686477e4a8e65 Mon Sep 17 00:00:00 2001 From: Ajay Ghanwat Date: Mon, 3 Aug 2026 00:54:29 +0530 Subject: [PATCH] fix: recover PWA clients without navigation reload --- app/docs.test.ts | 3 ++- public/pwa-recover.js | 33 ++++++++++++++++++--------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/app/docs.test.ts b/app/docs.test.ts index cc48add1..149a713c 100644 --- a/app/docs.test.ts +++ b/app/docs.test.ts @@ -139,7 +139,8 @@ test("site includes core guides and production configuration", () => { expect(config).toContain("head: ''"); const recovery = readFileSync(join(root, "public", "pwa-recover.js"), "utf8"); expect(recovery).toContain('updateViaCache: "none"'); - expect(recovery).toContain("registration.update()"); + expect(recovery).toContain("requestIdleCallback"); + expect(recovery).not.toContain("location.reload()"); expect(config).toContain('pattern: "^https://wrnexusjs\\\\.dev/"'); }); diff --git a/public/pwa-recover.js b/public/pwa-recover.js index fc9283e3..32bd4247 100644 --- a/public/pwa-recover.js +++ b/public/pwa-recover.js @@ -1,4 +1,4 @@ -/* global location, navigator, sessionStorage, window */ +/* global navigator, window */ (function () { if (!("serviceWorker" in navigator)) return; @@ -19,19 +19,22 @@ } } - var reloading = false; - navigator.serviceWorker.addEventListener("controllerchange", function () { - var key = "wrnexus-pwa-controller-" + version; - if (reloading || sessionStorage.getItem(key)) return; - reloading = true; - sessionStorage.setItem(key, "1"); - location.reload(); - }); + var recover = function () { + navigator.serviceWorker + .getRegistration() + .then(function (registration) { + if ( + registration && + registration.active && + registration.active.scriptURL.includes(version) + ) { + return; + } + return navigator.serviceWorker.register(workerUrl, { updateViaCache: "none" }); + }) + .catch(function () {}); + }; - navigator.serviceWorker - .register(workerUrl, { updateViaCache: "none" }) - .then(function (registration) { - return registration.update(); - }) - .catch(function () {}); + if ("requestIdleCallback" in window) window.requestIdleCallback(recover, { timeout: 2000 }); + else window.setTimeout(recover, 0); })();