2022-12-18 08:29:16 +09:00
|
|
|
import { useRegisterSW } from 'virtual:pwa-register/vue'
|
|
|
|
|
2022-12-28 23:08:03 +09:00
|
|
|
export default defineNuxtPlugin(() => {
|
2022-12-18 08:29:16 +09:00
|
|
|
const online = useOnline()
|
2023-01-08 23:12:25 +09:00
|
|
|
const registrationError = ref(false)
|
|
|
|
const swActivated = ref(false)
|
|
|
|
|
2023-01-15 05:58:52 +09:00
|
|
|
// https://thomashunter.name/posts/2021-12-11-detecting-if-pwa-twa-is-installed
|
|
|
|
const ua = navigator.userAgent
|
|
|
|
const ios = ua.match(/iPhone|iPad|iPod/)
|
|
|
|
const standalone = window.matchMedia('(display-mode: standalone)').matches
|
|
|
|
const isInstalled = !!(standalone || (ios && !ua.match(/Safari/)))
|
|
|
|
|
2023-01-08 23:12:25 +09:00
|
|
|
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 */)
|
|
|
|
}
|
2022-12-18 08:29:16 +09:00
|
|
|
|
|
|
|
const {
|
2022-12-28 10:06:54 +09:00
|
|
|
needRefresh, updateServiceWorker,
|
2022-12-18 08:29:16 +09:00
|
|
|
} = useRegisterSW({
|
|
|
|
immediate: true,
|
2023-01-08 23:12:25 +09:00
|
|
|
onRegisterError() {
|
|
|
|
registrationError.value = true
|
|
|
|
},
|
2022-12-18 08:29:16 +09:00
|
|
|
onRegisteredSW(swUrl, r) {
|
2023-01-08 23:12:25 +09:00
|
|
|
// 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)
|
2022-12-18 08:29:16 +09:00
|
|
|
})
|
2023-01-08 23:12:25 +09:00
|
|
|
}
|
2022-12-18 08:29:16 +09:00
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
const close = async () => {
|
|
|
|
needRefresh.value = false
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2022-12-28 23:08:03 +09:00
|
|
|
provide: {
|
|
|
|
pwa: reactive({
|
2023-01-15 05:58:52 +09:00
|
|
|
isInstalled,
|
2023-01-08 23:12:25 +09:00
|
|
|
swActivated,
|
|
|
|
registrationError,
|
2022-12-28 23:08:03 +09:00
|
|
|
needRefresh,
|
|
|
|
updateServiceWorker,
|
|
|
|
close,
|
|
|
|
}),
|
|
|
|
},
|
2022-12-18 08:29:16 +09:00
|
|
|
}
|
2022-12-28 23:08:03 +09:00
|
|
|
})
|