fix (maybe) for page not reloading after updating service worker

This commit is contained in:
Jesse D. McDonald 2020-05-11 13:04:00 -05:00
parent 994880f454
commit d1439b3f09
2 changed files with 41 additions and 32 deletions

View File

@ -786,24 +786,29 @@ $(function (){
Promise.resolve().then(async () => {
const wb = new Workbox('sw.js');
let latest_sw = null;
function showSkipWaitingPrompt(event) {
if (confirmBox) {
confirmBox.close({ ignoreDelay: true });
}
latest_sw = event.sw;
if (!confirmBox) {
confirmBox = new jBox('Confirm', {
attach: null,
content: "A new version is available. Update the page?",
confirmButton: `<span class="update-confirm-button">Update</span>`,
cancelButton: 'Not now',
closeOnConfirm: false,
confirm() {
async confirm() {
/* The SW should signal us to reload, but do it after 20s regardless. */
setTimeout(() => { window.location.reload(); }, 20000);
messageSW(event.sw, {type: 'SKIP_WAITING'});
messageSW(latest_sw, {type: 'SKIP_WAITING'});
$('.update-confirm-button').text('Updating…');
},
onClose() {
if (confirmBox === this) {
confirmBox = null;
}
},
onCloseComplete() {
this.destroy();
},
@ -811,6 +816,11 @@ $(function (){
confirmBox.open();
}
}
function reloadForUpdate(event) {
window.location.reload();
}
wb.addEventListener('installed', (event) => {
try {
@ -822,23 +832,18 @@ $(function (){
}
});
wb.addEventListener('controlling', (event) => {
if (event.isUpdate) {
window.location.reload();
}
});
wb.addEventListener('waiting', showSkipWaitingPrompt);
wb.addEventListener('externalwaiting', showSkipWaitingPrompt);
wb.addEventListener('controlling', reloadForUpdate);
wb.addEventListener('externalactivated', reloadForUpdate);
const registration = await wb.register();
if ('update' in registration) {
/* Check for updates every 4h without reloading the page. */
setInterval(() => { registration.update(); }, 4*3600*1000);
} else {
console.log('service worker update method not supported, disabling update checks');
}
setInterval(() => { wb.update(); }, 4*3600*1000);
window.Admin.workbox = wb;
}).catch((err) => {
console.error('failed to register the service worker', err);
disableNotify();

4
sw.js
View File

@ -14,3 +14,7 @@ addEventListener('message', (event) => {
skipWaiting();
}
});
self.addEventListener('activate', (event) => {
event.waitUntil(clients.claim());
});