From 96af7291ea5b2c5ed6372e7b6f7725e67c69f1ba Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Fri, 10 Jun 2022 04:33:42 +0800 Subject: [PATCH] fix(PWA): sometimes update notification is not triggered --- assets/js/pwa/app.js | 57 +++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 35 deletions(-) diff --git a/assets/js/pwa/app.js b/assets/js/pwa/app.js index 9eb1a03..ab4b174 100644 --- a/assets/js/pwa/app.js +++ b/assets/js/pwa/app.js @@ -3,50 +3,37 @@ layout: compress permalink: '/app.js' --- -const keyWaiting = 'sw-waiting'; const $notification = $('#notification'); const $btnRefresh = $('#notification .toast-body>button'); -function skipWating(registration) { - registration.waiting.postMessage('SKIP_WAITING'); - localStorage.removeItem(keyWaiting); -} - if ('serviceWorker' in navigator) { /* Registering Service Worker */ navigator.serviceWorker.register('{{ "/sw.js" | relative_url }}') .then(registration => { - if (registration) { - registration.addEventListener('updatefound', () => { - let serviceWorker = registration.installing; - serviceWorker.addEventListener('statechange', () => { - if (serviceWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - $notification.toast('show'); - /* in case the user ignores the notification */ - localStorage.setItem(keyWaiting, true); - } - } - }); - }); - - $btnRefresh.click(() => { - skipWating(registration); - $notification.toast('hide'); - }); - - if (localStorage.getItem(keyWaiting)) { - if (registration.waiting) { - /* there's a new Service Worker waiting to be activated */ - $notification.toast('show'); - } else { - /* closed all open pages after receiving notification */ - localStorage.removeItem(keyWaiting); - } - } + /* in case the user ignores the notification */ + if (registration.waiting) { + $notification.toast('show'); } - }); + + registration.addEventListener('updatefound', () => { + registration.installing.addEventListener('statechange', () => { + if (registration.waiting) { + if (navigator.serviceWorker.controller) { + $notification.toast('show'); + } + } + }); + }); + + $btnRefresh.click(() => { + if (registration.waiting) { + registration.waiting.postMessage('SKIP_WAITING'); + } + $notification.toast('hide'); + }); + } + ); let refreshing = false;