feat: 添加 PWA 安装支持,包括安装横幅和按钮;更新国际化文本;配置 PWA 清单和缓存策略
This commit is contained in:
58
packages/distribute/composables/usePWAInstall.ts
Normal file
58
packages/distribute/composables/usePWAInstall.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { ref, onMounted } from 'vue'
|
||||
|
||||
export function usePWAInstall() {
|
||||
const deferredPrompt = ref<any>(null)
|
||||
const canInstall = ref(false)
|
||||
const isInstalled = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
// 检查是否已安装
|
||||
if (window.matchMedia('(display-mode: standalone)').matches) {
|
||||
isInstalled.value = true
|
||||
return
|
||||
}
|
||||
|
||||
// 监听安装提示事件
|
||||
window.addEventListener('beforeinstallprompt', (e) => {
|
||||
e.preventDefault()
|
||||
deferredPrompt.value = e
|
||||
canInstall.value = true
|
||||
})
|
||||
|
||||
// 监听安装成功事件
|
||||
window.addEventListener('appinstalled', () => {
|
||||
deferredPrompt.value = null
|
||||
canInstall.value = false
|
||||
isInstalled.value = true
|
||||
})
|
||||
})
|
||||
|
||||
async function install() {
|
||||
if (!deferredPrompt.value) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
await deferredPrompt.value.prompt()
|
||||
const { outcome } = await deferredPrompt.value.userChoice
|
||||
|
||||
if (outcome === 'accepted') {
|
||||
deferredPrompt.value = null
|
||||
canInstall.value = false
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
catch (error) {
|
||||
console.error('安装失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
canInstall,
|
||||
isInstalled,
|
||||
install,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user