feat: 重构 usePWAInstall 逻辑,优化 iOS 设备检测和安装提示处理
This commit is contained in:
@@ -3,39 +3,33 @@ interface BeforeInstallPromptEvent extends Event {
|
||||
userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
|
||||
}
|
||||
|
||||
export function usePWAInstall() {
|
||||
const deferredPrompt = ref<BeforeInstallPromptEvent | null>(null);
|
||||
const canInstall = ref(false);
|
||||
const isInstalled = ref(false);
|
||||
// 全局状态,在模块加载时就创建
|
||||
const deferredPrompt = ref<BeforeInstallPromptEvent | null>(null);
|
||||
const canInstall = ref(false);
|
||||
const isInstalled = ref(false);
|
||||
|
||||
// 检测是否是 iOS 设备
|
||||
function isIOS() {
|
||||
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
|
||||
// 检测是否是 iOS 设备
|
||||
function isIOS() {
|
||||
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
|
||||
}
|
||||
|
||||
// 检测是否是 iOS Safari(未安装)
|
||||
function isIOSSafari() {
|
||||
return isIOS() && !(window.navigator as any).standalone;
|
||||
}
|
||||
|
||||
// 在模块加载时就设置监听器(不等待组件挂载)
|
||||
if (typeof window !== "undefined") {
|
||||
// 检查是否已安装
|
||||
if (window.matchMedia("(display-mode: standalone)").matches) {
|
||||
isInstalled.value = true;
|
||||
console.log("[PWA] Already installed (standalone mode)");
|
||||
}
|
||||
|
||||
// 检测是否是 iOS Safari(未安装)
|
||||
function isIOSSafari() {
|
||||
return isIOS() && !(window.navigator as any).standalone;
|
||||
else if ((window.navigator as any).standalone === true) {
|
||||
isInstalled.value = true;
|
||||
console.log("[PWA] Already installed (iOS standalone)");
|
||||
}
|
||||
|
||||
// 使用 onMounted 确保在客户端环境执行
|
||||
onMounted(() => {
|
||||
console.log("[PWA] usePWAInstall mounted");
|
||||
|
||||
// 检查是否已安装
|
||||
if (window.matchMedia("(display-mode: standalone)").matches) {
|
||||
isInstalled.value = true;
|
||||
console.log("[PWA] Already installed (standalone mode)");
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查 iOS Safari 独立模式
|
||||
if ((window.navigator as any).standalone === true) {
|
||||
isInstalled.value = true;
|
||||
console.log("[PWA] Already installed (iOS standalone)");
|
||||
return;
|
||||
}
|
||||
|
||||
else {
|
||||
// 监听安装提示事件(仅 Android/Chrome)
|
||||
window.addEventListener("beforeinstallprompt", (e: Event) => {
|
||||
console.log("[PWA] beforeinstallprompt event fired");
|
||||
@@ -57,6 +51,14 @@ export function usePWAInstall() {
|
||||
console.log("[PWA] iOS Safari detected, showing install button");
|
||||
canInstall.value = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function usePWAInstall() {
|
||||
onMounted(() => {
|
||||
console.log("[PWA] usePWAInstall mounted");
|
||||
console.log("[PWA] canInstall:", canInstall.value);
|
||||
console.log("[PWA] isInstalled:", isInstalled.value);
|
||||
});
|
||||
|
||||
async function install() {
|
||||
|
||||
Reference in New Issue
Block a user