fix(pwa): handle sw registration error and status (#858)
This commit is contained in:
parent
5f07fd2515
commit
e92a983947
2 changed files with 41 additions and 21 deletions
|
@ -2,30 +2,48 @@ import { useRegisterSW } from 'virtual:pwa-register/vue'
|
|||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const online = useOnline()
|
||||
const registrationError = ref(false)
|
||||
const swActivated = ref(false)
|
||||
|
||||
const registerPeriodicSync = (swUrl: string, r: ServiceWorkerRegistration) => {
|
||||
setInterval(async () => {
|
||||
if (!online.value)
|
||||
return
|
||||
|
||||
const resp = await fetch(swUrl, {
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
'cache': 'no-store',
|
||||
'cache-control': 'no-cache',
|
||||
},
|
||||
})
|
||||
|
||||
if (resp?.status === 200)
|
||||
await r.update()
|
||||
}, 60 * 60 * 1000 /* 1 hour */)
|
||||
}
|
||||
|
||||
const {
|
||||
needRefresh, updateServiceWorker,
|
||||
} = useRegisterSW({
|
||||
immediate: true,
|
||||
onRegisterError() {
|
||||
registrationError.value = true
|
||||
},
|
||||
onRegisteredSW(swUrl, r) {
|
||||
if (!r || r.installing)
|
||||
return
|
||||
|
||||
setInterval(async () => {
|
||||
if (!online.value)
|
||||
return
|
||||
|
||||
const resp = await fetch(swUrl, {
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
'cache': 'no-store',
|
||||
'cache-control': 'no-cache',
|
||||
},
|
||||
// should add support in pwa plugin
|
||||
if (r?.active?.state === 'activated') {
|
||||
swActivated.value = true
|
||||
registerPeriodicSync(swUrl, r)
|
||||
}
|
||||
else if (r?.installing) {
|
||||
r.installing.addEventListener('statechange', (e) => {
|
||||
const sw = e.target as ServiceWorker
|
||||
swActivated.value = sw.state === 'activated'
|
||||
if (swActivated.value)
|
||||
registerPeriodicSync(swUrl, r)
|
||||
})
|
||||
|
||||
if (resp?.status === 200)
|
||||
await r.update()
|
||||
}, 60 * 60 * 1000 /* 1 hour */)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
|
@ -36,6 +54,8 @@ export default defineNuxtPlugin(() => {
|
|||
return {
|
||||
provide: {
|
||||
pwa: reactive({
|
||||
swActivated,
|
||||
registrationError,
|
||||
needRefresh,
|
||||
updateServiceWorker,
|
||||
close,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue