From 6e65ecd52c783bcf6fd6d2a994245e524c3edc3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=B8=85?= Date: Tue, 4 Dec 2018 18:30:24 +0800 Subject: [PATCH] fix reloadSW no trigger error --- .eslintignore | 3 ++- src/global.js | 55 +++++++++++++++++++++++++++++---------------------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/.eslintignore b/.eslintignore index 18275c1c..43ab7824 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,2 +1,3 @@ /functions/mock/** -/scripts \ No newline at end of file +/scripts +/config \ No newline at end of file diff --git a/src/global.js b/src/global.js index fb4e46ca..62f8cceb 100644 --- a/src/global.js +++ b/src/global.js @@ -9,9 +9,38 @@ window.addEventListener('sw.offline', () => { // Pop up a prompt on the page asking the user if they want to use the latest version window.addEventListener('sw.updated', e => { + const reloadSW = async () => { + // Check if there is sw whose state is waiting in ServiceWorkerRegistration + // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration + const worker = e.detail && e.detail.waiting; + if (!worker) { + return Promise.resolve(); + } + // Send skip-waiting event to waiting SW with MessageChannel + await new Promise((resolve, reject) => { + const channel = new MessageChannel(); + channel.port1.onmessage = event => { + if (event.data.error) { + reject(event.data.error); + } else { + resolve(event.data); + } + }; + worker.postMessage({ type: 'skip-waiting' }, [channel.port2]); + }); + // Refresh current page to use the updated HTML and other assets after SW has skiped waiting + window.location.reload(true); + return true; + }; const key = `open${Date.now()}`; const btn = ( - ); @@ -20,28 +49,6 @@ window.addEventListener('sw.updated', e => { description: formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }), btn, key, - onClose: async () => { - // Check if there is sw whose state is waiting in ServiceWorkerRegistration - // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration - const worker = e.detail && e.detail.waiting; - if (!worker) { - return Promise.resolve(); - } - // Send skip-waiting event to waiting SW with MessageChannel - await new Promise((resolve, reject) => { - const channel = new MessageChannel(); - channel.port1.onmessage = event => { - if (event.data.error) { - reject(event.data.error); - } else { - resolve(event.data); - } - }; - worker.postMessage({ type: 'skip-waiting' }, [channel.port2]); - }); - // Refresh current page to use the updated HTML and other assets after SW has skiped waiting - window.location.reload(true); - return true; - }, + onClose: async () => {}, }); }); -- GitLab