75 lines
2.2 KiB
TypeScript
75 lines
2.2 KiB
TypeScript
import { Capacitor } from '@capacitor/core'
|
|
import { ElMessageBox } from 'element-plus'
|
|
import { translate } from '../i18n'
|
|
|
|
let updatePromptVisible = false
|
|
|
|
function serviceWorkerUrl() {
|
|
// Vite's BASE_URL is normally a path such as "/" rather than an absolute
|
|
// URL. The URL constructor requires an absolute base in browsers.
|
|
return new URL(`${import.meta.env.BASE_URL}sw.js`, window.location.origin).toString()
|
|
}
|
|
|
|
async function promptToRefresh(registration: ServiceWorkerRegistration) {
|
|
const waitingWorker = registration.waiting
|
|
if (!waitingWorker || updatePromptVisible) return
|
|
|
|
updatePromptVisible = true
|
|
try {
|
|
await ElMessageBox.confirm(
|
|
translate('updates.pwaMessage'),
|
|
translate('updates.pwaTitle'),
|
|
{
|
|
confirmButtonText: translate('updates.refresh'),
|
|
cancelButtonText: translate('updates.later'),
|
|
type: 'info',
|
|
},
|
|
)
|
|
waitingWorker.postMessage({ type: 'SKIP_WAITING' })
|
|
} catch {
|
|
// Keeping the current version is an intentional, safe user choice.
|
|
} finally {
|
|
updatePromptVisible = false
|
|
}
|
|
}
|
|
|
|
export async function initializePwa() {
|
|
if (
|
|
Capacitor.isNativePlatform() ||
|
|
!('serviceWorker' in navigator) ||
|
|
!window.isSecureContext
|
|
) {
|
|
return
|
|
}
|
|
|
|
try {
|
|
const registration = await navigator.serviceWorker.register(serviceWorkerUrl())
|
|
let refreshing = false
|
|
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
|
if (refreshing) return
|
|
refreshing = true
|
|
window.location.reload()
|
|
})
|
|
|
|
const watchForUpdate = () => {
|
|
const worker = registration.installing
|
|
if (!worker) return
|
|
worker.addEventListener('statechange', () => {
|
|
if (worker.state === 'installed') {
|
|
void promptToRefresh(registration)
|
|
}
|
|
})
|
|
}
|
|
|
|
registration.addEventListener('updatefound', watchForUpdate)
|
|
watchForUpdate()
|
|
// Browsers can otherwise throttle routine update checks; a normal app
|
|
// launch should still discover a newly deployed service worker promptly.
|
|
await registration.update()
|
|
await promptToRefresh(registration)
|
|
} catch (error) {
|
|
// PWA installation and caching are progressive enhancements.
|
|
console.warn('[pwa] service worker registration failed', error)
|
|
}
|
|
}
|