Skip to content

Commit 96af729

Browse files
committed
fix(PWA): sometimes update notification is not triggered
1 parent 4c45f37 commit 96af729

File tree

1 file changed

+19
-32
lines changed

1 file changed

+19
-32
lines changed

assets/js/pwa/app.js

Lines changed: 19 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,37 @@ layout: compress
33
permalink: '/app.js'
44
---
55

6-
const keyWaiting = 'sw-waiting';
76
const $notification = $('#notification');
87
const $btnRefresh = $('#notification .toast-body>button');
98

10-
function skipWating(registration) {
11-
registration.waiting.postMessage('SKIP_WAITING');
12-
localStorage.removeItem(keyWaiting);
13-
}
14-
159
if ('serviceWorker' in navigator) {
1610
/* Registering Service Worker */
1711
navigator.serviceWorker.register('{{ "/sw.js" | relative_url }}')
1812
.then(registration => {
19-
if (registration) {
20-
registration.addEventListener('updatefound', () => {
21-
let serviceWorker = registration.installing;
22-
23-
serviceWorker.addEventListener('statechange', () => {
24-
if (serviceWorker.state === 'installed') {
25-
if (navigator.serviceWorker.controller) {
26-
$notification.toast('show');
27-
/* in case the user ignores the notification */
28-
localStorage.setItem(keyWaiting, true);
29-
}
30-
}
31-
});
32-
});
3313

34-
$btnRefresh.click(() => {
35-
skipWating(registration);
36-
$notification.toast('hide');
37-
});
14+
/* in case the user ignores the notification */
15+
if (registration.waiting) {
16+
$notification.toast('show');
17+
}
3818

39-
if (localStorage.getItem(keyWaiting)) {
19+
registration.addEventListener('updatefound', () => {
20+
registration.installing.addEventListener('statechange', () => {
4021
if (registration.waiting) {
41-
/* there's a new Service Worker waiting to be activated */
42-
$notification.toast('show');
43-
} else {
44-
/* closed all open pages after receiving notification */
45-
localStorage.removeItem(keyWaiting);
22+
if (navigator.serviceWorker.controller) {
23+
$notification.toast('show');
24+
}
4625
}
26+
});
27+
});
28+
29+
$btnRefresh.click(() => {
30+
if (registration.waiting) {
31+
registration.waiting.postMessage('SKIP_WAITING');
4732
}
48-
}
49-
});
33+
$notification.toast('hide');
34+
});
35+
}
36+
);
5037

5138
let refreshing = false;
5239

0 commit comments

Comments
 (0)