jsp 网站开发环境,唐山seo排名外包,免备案域名是什么,个人网站建设的论文手头的项目有个需求需要检测PWA是否已经安装#xff0c;安装了导航下载就不显示#xff0c;没有安装就需要显示。在网上找了蛮久#xff0c;也问了chatgpt#xff0c;主要提供以下三种方法#xff0c;
1、判断 navigator.getInstalledRelatedApps() 是否有返回值
此方法…手头的项目有个需求需要检测PWA是否已经安装安装了导航下载就不显示没有安装就需要显示。在网上找了蛮久也问了chatgpt主要提供以下三种方法
1、判断 navigator.getInstalledRelatedApps() 是否有返回值
此方法需要在 PWA 的 manifest 里先声明 related_application具体代码如下。
// manifest.webmanifest文件
{name: TestApp,short_name: TestApp,start_url: https://example.com,display: standalone,background_color: #181818,theme_color: #181818,icons: [{sizes: 192x192,src: https://xxx.png,type: image/png}],related_applications: [{platform: webapp,url: https://example.com,id: com.example.app}]
}// 入口判断
if (navigator.getInstalledRelatedApps) {navigator.getInstalledRelatedApps().then(apps {if (apps.length 0) {console.log(Found installed related apps:, apps);} else {console.log(No related apps installed.);}}).catch(error {console.error(Error fetching installed apps:, error);});
} else {console.log(getInstalledRelatedApps is not supported on this browser.);
}当时我加了 related_applications 字段后navigator.getInstalledRelatedApps() 返回的还是一个空数组不知道是不是姿势不对。有兴趣的小伙伴可以自己尝试以下。
2、在 iOS 上通过 navigator.standalone 属性可以检测 PWA 是否已添加到主屏幕。
function inPwa () {return window.matchMedia((display-mode: standalone)).matches) || window.navigator.standalone || document.referrer.includes(android-app://)
}此方法我试过H5页面不能判断成功但是在打开的PWA程序中是有效的。
3、监听 beforeinstallprompt 判断是否安装
store.state.isPwaInstalled true
window.addEventListener(beforeinstallprompt, (e) {console.log(PWA 未安装)e.preventDefault()window.deferredPrompt estore.state.isPwaInstalled false;
})// 如果没有触发 beforeinstallprompt则说明可能已被安装
window.addEventListener(appinstalled, () {store.state.isPwaInstalled true;
});这个方法我一直误以为是在点击安装PWA的时候才会判断实际上每次进入主入口都会监听beforeinstallprompt所以可以先默认为已经下载了PWA然后监听beforeinstallprompt如果能监听到说明当前没有下载PWA否则就保持默认已经下载了。还可以增加监听appinstalled当前点击下载以后将下载弹窗隐藏。