refactor: use nuxt plugin to provide pwa helpers globally (#604)
This commit is contained in:
parent
73cec49cf0
commit
726a581add
4 changed files with 15 additions and 23 deletions
45
plugins/pwa.client.ts
Normal file
45
plugins/pwa.client.ts
Normal file
|
@ -0,0 +1,45 @@
|
|||
import { useRegisterSW } from 'virtual:pwa-register/vue'
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const online = useOnline()
|
||||
|
||||
const {
|
||||
needRefresh, updateServiceWorker,
|
||||
} = useRegisterSW({
|
||||
immediate: 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',
|
||||
},
|
||||
})
|
||||
|
||||
if (resp?.status === 200)
|
||||
await r.update()
|
||||
}, 60 * 60 * 1000 /* 1 hour */)
|
||||
},
|
||||
})
|
||||
|
||||
const close = async () => {
|
||||
needRefresh.value = false
|
||||
}
|
||||
|
||||
return {
|
||||
provide: {
|
||||
pwa: reactive({
|
||||
needRefresh,
|
||||
updateServiceWorker,
|
||||
close,
|
||||
}),
|
||||
},
|
||||
}
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue