Skip to content

Commit

Permalink
fix(PWA): sometimes update notification is not triggered
Browse files Browse the repository at this point in the history
  • Loading branch information
cotes2020 committed Jun 10, 2022
1 parent 4c45f37 commit 96af729
Showing 1 changed file with 19 additions and 32 deletions.
51 changes: 19 additions & 32 deletions assets/js/pwa/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
/* in case the user ignores the notification */
if (registration.waiting) {
$notification.toast('show');
}

if (localStorage.getItem(keyWaiting)) {
registration.addEventListener('updatefound', () => {
registration.installing.addEventListener('statechange', () => {
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);
if (navigator.serviceWorker.controller) {
$notification.toast('show');
}
}
});
});

$btnRefresh.click(() => {
if (registration.waiting) {
registration.waiting.postMessage('SKIP_WAITING');
}
}
});
$notification.toast('hide');
});
}
);

let refreshing = false;

Expand Down

0 comments on commit 96af729

Please sign in to comment.