fix(PWA): sometimes update notification is not triggered

This commit is contained in:
Cotes Chung 2022-06-10 04:33:42 +08:00
parent 4c45f3788e
commit 96af7291ea
No known key found for this signature in database
GPG key ID: 0D9E54843167A808

View file

@ -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') {
/* 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');
/* in case the user ignores the notification */
localStorage.setItem(keyWaiting, true);
}
}
});
});
$btnRefresh.click(() => {
skipWating(registration);
if (registration.waiting) {
registration.waiting.postMessage('SKIP_WAITING');
}
$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);
}
}
}
});
);
let refreshing = false;