From 933a1e4a36a7283e224649427ea76ac39bdd2fb2 Mon Sep 17 00:00:00 2001 From: A R R R Associates Date: Fri, 10 Jul 2026 12:34:50 +0530 Subject: [PATCH] Fix service worker returning CSS for page navigation --- app/ui/static/pwa/sw.js | 55 ++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/app/ui/static/pwa/sw.js b/app/ui/static/pwa/sw.js index 922d6b9..e0758cd 100644 --- a/app/ui/static/pwa/sw.js +++ b/app/ui/static/pwa/sw.js @@ -1,4 +1,4 @@ -const CACHE_VERSION = 'arrr-erp-pwa-v1'; +const CACHE_VERSION = 'arrr-erp-pwa-v2-navigation-fix'; const CORE_ASSETS = [ '/manifest.webmanifest', '/static/css/theme_tokens.css', @@ -8,14 +8,20 @@ const CORE_ASSETS = [ self.addEventListener('install', (event) => { event.waitUntil( - caches.open(CACHE_VERSION).then((cache) => cache.addAll(CORE_ASSETS)).catch(() => undefined) + caches.open(CACHE_VERSION) + .then((cache) => cache.addAll(CORE_ASSETS)) + .catch(() => undefined) ); self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil( - caches.keys().then((keys) => Promise.all(keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key)))) + caches.keys().then((keys) => Promise.all( + keys + .filter((key) => key !== CACHE_VERSION) + .map((key) => caches.delete(key)) + )) ); self.clients.claim(); }); @@ -27,16 +33,47 @@ self.addEventListener('fetch', (event) => { const url = new URL(request.url); if (url.origin !== self.location.origin) return; + // Cache static assets only. Never substitute a CSS response for an HTML page. if (url.pathname.startsWith('/static/')) { event.respondWith( - caches.match(request).then((cached) => cached || fetch(request).then((response) => { - const copy = response.clone(); - caches.open(CACHE_VERSION).then((cache) => cache.put(request, copy)).catch(() => undefined); - return response; - })) + caches.match(request).then((cached) => { + if (cached) return cached; + + return fetch(request).then((response) => { + if (response && response.ok) { + const copy = response.clone(); + caches.open(CACHE_VERSION) + .then((cache) => cache.put(request, copy)) + .catch(() => undefined); + } + return response; + }); + }) ); return; } - event.respondWith(fetch(request).catch(() => caches.match('/static/css/theme_tokens.css'))); + // Application pages, login, API calls and downloads remain network-first. + // If the network is unavailable, return a valid HTML response instead of CSS. + event.respondWith( + fetch(request).catch(() => { + if (request.mode === 'navigate') { + return new Response( + 'Offline | Audit Firm ERP

You are offline

The ERP could not reach the server. Check your internet connection and refresh this page.

', + { + status: 503, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store' + } + } + ); + } + + return new Response('', { + status: 503, + headers: { 'Cache-Control': 'no-store' } + }); + }) + ); });