feat(pwa): add install PWA widget (#1451)

This commit is contained in:
Joaquín Sánchez 2023-01-25 16:26:51 +01:00 committed by GitHub
parent 3c888d3914
commit f96cdae1ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 73 additions and 1 deletions

View file

@ -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,