From 4d95c17e86376c0d025d2b99281650aa7048e29d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20S=C3=A1nchez?= Date: Mon, 23 Sep 2024 14:45:46 +0200 Subject: [PATCH] fix: add new service worker (#2971) --- config/pwa.ts | 2 +- modules/pwa/index.ts | 5 +++++ public/sw.js | 24 ++++++++++++++++++++++++ service-worker/{sw.ts => elk-sw.ts} | 1 + 4 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 public/sw.js rename service-worker/{sw.ts => elk-sw.ts} (99%) diff --git a/config/pwa.ts b/config/pwa.ts index 4ae5e35b..a77b4678 100644 --- a/config/pwa.ts +++ b/config/pwa.ts @@ -7,7 +7,7 @@ export const pwa: VitePWANuxtOptions = { disable: /* temporarily test in CI isPreview || */ (isDevelopment && process.env.VITE_DEV_PWA !== 'true'), scope: '/', srcDir: './service-worker', - filename: 'sw.ts', + filename: 'elk-sw.ts', strategies: 'injectManifest', injectRegister: false, includeManifestIcons: false, diff --git a/modules/pwa/index.ts b/modules/pwa/index.ts index cb3c218c..0cf91d59 100644 --- a/modules/pwa/index.ts +++ b/modules/pwa/index.ts @@ -202,6 +202,11 @@ export default defineNuxtModule({ 'Cache-Control': 'public, max-age=0, must-revalidate', }, } + nitroConfig.routeRules!['/elk-sw.js'] = { + headers: { + 'Cache-Control': 'public, max-age=0, must-revalidate', + }, + } for (const locale of pwaLocales) { nitroConfig.routeRules![`/manifest-${locale.code}.webmanifest`] = { headers: { diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 00000000..433b7e49 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,24 @@ +// DON'T REMOVE THIS FILE: IT IS THE OLD sw.js +self.addEventListener('install', (e) => { + self.skipWaiting(); +}); +self.addEventListener('activate', (e) => { + self.registration.unregister() + .then(() => self.clients.matchAll()) + .then((clients) => { + clients.forEach((client) => { + if (client instanceof WindowClient) + client.navigate(client.url); + }); + return Promise.resolve(); + }) + .then(() => { + self.caches.keys().then((cacheNames) => { + Promise.all( + cacheNames.map((cacheName) => { + return self.caches.delete(cacheName); + }) + ); + }) + }); +}); diff --git a/service-worker/sw.ts b/service-worker/elk-sw.ts similarity index 99% rename from service-worker/sw.ts rename to service-worker/elk-sw.ts index 12bedbea..d6a516b1 100644 --- a/service-worker/sw.ts +++ b/service-worker/elk-sw.ts @@ -43,6 +43,7 @@ if (import.meta.env.PROD) { /^\/emojis\//, // exclude sw: if the user navigates to it, fallback to index.html /^\/sw.js$/, + /^\/elk-sw.js$/, // exclude webmanifest: has its own cache /^\/manifest-(.*).webmanifest$/, ]