"use client"; import { useEffect, useState } from "react"; import { Download, X } from "lucide-react"; type BeforeInstallPromptEvent = Event & { prompt: () => Promise; userChoice: Promise<{ outcome: "accepted" | "dismissed" }>; }; const DISMISS_KEY = "dylive_pwa_install_dismissed"; function isStandalone(): boolean { if (typeof window === "undefined") return false; if (window.matchMedia("(display-mode: standalone)").matches) return true; return Boolean((navigator as Navigator & { standalone?: boolean }).standalone); } export function PwaInstallBanner() { const [deferred, setDeferred] = useState(null); const [visible, setVisible] = useState(false); const [iosHint, setIosHint] = useState(false); const [androidHint, setAndroidHint] = useState(false); const [status, setStatus] = useState(""); const [busy, setBusy] = useState(false); useEffect(() => { if (typeof window === "undefined") return; if (isStandalone()) return; if (localStorage.getItem(DISMISS_KEY) === "1") return; const ua = navigator.userAgent || ""; const isIos = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); const isSafari = /Safari/.test(ua) && !/CriOS|FxiOS|EdgiOS|Chrome/.test(ua); const isAndroid = /Android/i.test(ua); const isChrome = /Chrome|CriOS/i.test(ua) && !/Edg/i.test(ua); const onBip = (e: Event) => { e.preventDefault(); setDeferred(e as BeforeInstallPromptEvent); setVisible(true); setIosHint(false); setAndroidHint(isAndroid); setStatus(""); }; window.addEventListener("beforeinstallprompt", onBip); const onInstalled = () => { setStatus("已添加。请看桌面是否出现 LiveRadar(可能带 Chrome 角标)。"); setVisible(true); setDeferred(null); }; window.addEventListener("appinstalled", onInstalled); if (isIos && isSafari) { setIosHint(true); setVisible(true); } else if (isAndroid) { setAndroidHint(true); setVisible(true); } return () => { window.removeEventListener("beforeinstallprompt", onBip); window.removeEventListener("appinstalled", onInstalled); }; }, []); if (!visible) return null; const dismiss = () => { localStorage.setItem(DISMISS_KEY, "1"); setVisible(false); setDeferred(null); }; const install = async () => { if (!deferred || busy) return; setBusy(true); setStatus(""); try { await deferred.prompt(); const choice = await deferred.userChoice; if (choice.outcome === "accepted") { setStatus( "若桌面/应用列表仍没有:国内无 Google 时「安装应用」常会静默失败。请改用 Chrome ⋮ →「添加到主屏幕」。", ); setAndroidHint(true); } else { setStatus("已取消。请用 Chrome 右上角 ⋮ →「添加到主屏幕」(不要点「安装应用」)。"); setAndroidHint(true); } } catch { setStatus("安装弹窗失败。请用 Chrome ⋮ →「添加到主屏幕」。"); setAndroidHint(true); } finally { setDeferred(null); setBusy(false); } }; return (

添加到主屏幕

{iosHint ? "Safari:底部分享 →「添加到主屏幕」。" : androidHint ? "国内网络请用:Chrome 右上角 ⋮ →「添加到主屏幕」。不要用「安装应用」(要连 Google,没翻墙常会装不上、桌面和应用列表都没有)。" : "可选添加到主屏幕,方便手机快速打开。"}

{status ? (

{status}

) : null}
{deferred ? ( ) : null}
); }