fix: fix service worker for real (#1258)

fixes #1243
This commit is contained in:
Nolan Lawson 2019-06-01 13:07:38 -07:00 committed by GitHub
parent a35f5ee2d9
commit 74230cfe8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 1 deletions

View File

@ -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)
})
}
})
}

View File

@ -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
}
})