feat(pwa): add install PWA widget (#1451)
This commit is contained in:
parent
3c888d3914
commit
f96cdae1ba
8 changed files with 73 additions and 1 deletions
|
@ -4,6 +4,7 @@ export default defineNuxtPlugin(() => {
|
|||
const online = useOnline()
|
||||
const registrationError = ref(false)
|
||||
const swActivated = ref(false)
|
||||
const showInstallPrompt = ref(false)
|
||||
|
||||
// https://thomashunter.name/posts/2021-12-11-detecting-if-pwa-twa-is-installed
|
||||
const ua = navigator.userAgent
|
||||
|
@ -57,10 +58,51 @@ export default defineNuxtPlugin(() => {
|
|||
needRefresh.value = false
|
||||
}
|
||||
|
||||
type InstallPromptEvent = Event & {
|
||||
prompt: () => void
|
||||
userChoice: Promise<{ outcome: 'dismissed' | 'accepted' }>
|
||||
}
|
||||
|
||||
let deferredPrompt: InstallPromptEvent | undefined
|
||||
|
||||
const beforeInstallPrompt = (e: Event) => {
|
||||
e.preventDefault()
|
||||
deferredPrompt = e as InstallPromptEvent
|
||||
showInstallPrompt.value = true
|
||||
}
|
||||
window.addEventListener('beforeinstallprompt', beforeInstallPrompt)
|
||||
window.addEventListener('appinstalled', () => {
|
||||
deferredPrompt = undefined
|
||||
showInstallPrompt.value = false
|
||||
})
|
||||
|
||||
const cancelInstall = () => {
|
||||
deferredPrompt = undefined
|
||||
showInstallPrompt.value = false
|
||||
window.removeEventListener('beforeinstallprompt', beforeInstallPrompt)
|
||||
}
|
||||
|
||||
const install = async () => {
|
||||
if (!showInstallPrompt.value || !deferredPrompt) {
|
||||
showInstallPrompt.value = false
|
||||
return
|
||||
}
|
||||
|
||||
showInstallPrompt.value = false
|
||||
await nextTick()
|
||||
deferredPrompt.prompt()
|
||||
const { outcome } = await deferredPrompt.userChoice
|
||||
if (outcome === 'dismissed')
|
||||
cancelInstall()
|
||||
}
|
||||
|
||||
return {
|
||||
provide: {
|
||||
pwa: reactive({
|
||||
isInstalled,
|
||||
showInstallPrompt,
|
||||
cancelInstall,
|
||||
install,
|
||||
swActivated,
|
||||
registrationError,
|
||||
needRefresh,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue