From 74230cfe8e256d0b259833ba43978e821c930def Mon Sep 17 00:00:00 2001 From: Nolan Lawson Date: Sat, 1 Jun 2019 13:07:38 -0700 Subject: [PATCH] fix: fix service worker for real (#1258) fixes #1243 --- src/routes/_utils/serviceWorkerClient.js | 13 ++++++++++++- src/service-worker.js | 11 +++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/routes/_utils/serviceWorkerClient.js b/src/routes/_utils/serviceWorkerClient.js index d846f083..ecb7ea73 100644 --- a/src/routes/_utils/serviceWorkerClient.js +++ b/src/routes/_utils/serviceWorkerClient.js @@ -1,11 +1,22 @@ import { snackbar } from '../_components/snackbar/snackbar' +async function skipWaiting () { + const reg = await navigator.serviceWorker.getRegistration() + if (!reg || !reg.waiting) { + return + } + reg.waiting.postMessage('skip-waiting') +} + function onUpdateFound (registration) { const newWorker = registration.installing newWorker.addEventListener('statechange', async () => { if (newWorker.state === 'installed' && navigator.serviceWorker.controller) { - snackbar.announce('App update available.', 'Reload', () => document.location.reload(true)) + snackbar.announce('App update available.', 'Reload', async () => { + await skipWaiting() + document.location.reload(true) + }) } }) } diff --git a/src/service-worker.js b/src/service-worker.js index d2b44488..31fa603d 100644 --- a/src/service-worker.js +++ b/src/service-worker.js @@ -35,6 +35,9 @@ self.addEventListener('install', event => { caches.open(WEBPACK_ASSETS).then(cache => cache.addAll(webpackAssets)), caches.open(ASSETS).then(cache => cache.addAll(assets)) ]) + // We shouldn't have to do this, but the previous page could be an old one, + // which would not send us a postMessage to skipWaiting(). + // See https://github.com/nolanlawson/pinafore/issues/1243 self.skipWaiting() })()) }) @@ -243,3 +246,11 @@ self.addEventListener('notificationclick', event => { } })()) }) + +self.addEventListener('message', (event) => { + switch (event.data) { + case 'skip-waiting': + self.skipWaiting() + break + } +})