From 63c342b69353ef14796d03ba07ff68ec696afd86 Mon Sep 17 00:00:00 2001 From: Julien Maille Date: Fri, 2 Jan 2026 13:45:33 +0100 Subject: [PATCH] IMP: improve service worker update flow to avoid stale cache and disruptive reloads --- index.html | 11 ----------- js/app.js | 22 +++++++++++++++++++--- sw.js | 9 +++++++-- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/index.html b/index.html index 765b62b..03e18df 100644 --- a/index.html +++ b/index.html @@ -735,16 +735,5 @@ - diff --git a/js/app.js b/js/app.js index 01b655e..b518630 100644 --- a/js/app.js +++ b/js/app.js @@ -649,17 +649,25 @@ if (e.target.closest('#delete-playlist-btn')) { .then(reg => { console.log('Service worker registered'); + if (reg.waiting) { + showUpdateNotification(reg.waiting); + } + reg.addEventListener('updatefound', () => { const newWorker = reg.installing; newWorker.addEventListener('statechange', () => { if (newWorker.state === 'installed' && navigator.serviceWorker.controller) { - showUpdateNotification(); + showUpdateNotification(newWorker); } }); }); }) .catch(err => console.log('Service worker not registered', err)); }); + + navigator.serviceWorker.addEventListener('controllerchange', () => { + window.location.reload(); + }); } let deferredPrompt; @@ -699,7 +707,7 @@ if (e.target.closest('#delete-playlist-btn')) { }); }); -function showUpdateNotification() { +function showUpdateNotification(worker) { const notification = document.createElement('div'); notification.className = 'update-notification'; notification.innerHTML = ` @@ -707,9 +715,17 @@ function showUpdateNotification() { Update Available

A new version of Monochrome is available.

- + `; document.body.appendChild(notification); + + document.getElementById('update-now-btn').addEventListener('click', () => { + if (worker) { + worker.postMessage({ action: 'skipWaiting' }); + } else { + window.location.reload(); + } + }); } function showInstallPrompt(deferredPrompt) { diff --git a/sw.js b/sw.js index 8ea7bf6..496589e 100644 --- a/sw.js +++ b/sw.js @@ -1,5 +1,5 @@ // sw.js -const SW_VERSION = 'monochrome-v6'; // Note To Self: Change Every Deploy +const SW_VERSION = 'monochrome-v7'; // Note To Self: Change Every Deploy const CACHE_NAME = `monochrome-${SW_VERSION}`; const ASSETS = [ @@ -31,12 +31,17 @@ const ASSETS = [ ]; self.addEventListener('install', event => { - self.skipWaiting(); event.waitUntil( caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS)) ); }); +self.addEventListener('message', (event) => { + if (event.data && event.data.action === 'skipWaiting') { + self.skipWaiting(); + } +}); + self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(keys =>