如何确定我的PWA是否已安装?
我知道onbeforeinstallprompt
事件将在有机会提示安装提示时触发,这表明该应用程序尚未安装。
我知道onappinstalled
将在安装应用程序的实际操作发生时触发,但是在随后的页面加载中,此事件不会再次触发。
我不能依靠将onappinstalled
的结果存储在LocalStorage中,因为可以在安装应用程序时清除LocalStorage,并且可以在不清除LocalStorage的情况下卸载应用程序。
display-mode
也没有用,因为即使安装了该应用程序,也可以切换到浏览器模式。
我怎么知道我的渐进式Web应用程序的安装状态?
答案 0 :(得分:3)
我认为您已经知道问题的答案,列出了所有可用的API和事件及其缺点,但您似乎正在寻求确认
因此,是的,没有办法知道,如果安装了PWA,则确切地确定为 100%,因为没有没有API 它
但是您提到的事件是互补的,因此,通过它们的结合,您可以非常接近
let isInstalled = localStorage.getItem('pwaInstalled') === '1' || false;
if (window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true) {
// User is currently navigating on the PWA so yes it's installed
localStorage.setItem('pwaInstalled', '1');
isInstalled = true;
} else {
//User is navigating in browser
window.addEventListener('beforeinstallprompt', () => {
localStorage.setItem('pwaInstalled', '0');
isInstalled = false;
//User can get an installation prompt meaning the app is not installed
});
window.addEventListener('onappinstalled', () => {
localStorage.setItem('pwaInstalled', '1');
isInstalled = true;
});
}
就像这样,您在本地存储中安装了标志pwaInstall,告诉您是否已安装该应用程序,如果清除了该数据,该标志将丢失,但是下次用户访问PWA或浏览器时,此标志可以再次正确设置到存储空间
如果用户删除该应用并访问浏览器,则该标志将被删除
请注意,
beforeinstallprompt event
是实验性的(非常类似于PWA中的所有内容),它在某些支持PWA安装的浏览器中不会启动/存在,并且在其他浏览器中可能并不完全准确(即使已经安装了该应用,也有可能触发它) 如果用户将其关闭,它也不会在90天之内触发
但是,由于要显示A2HS模式/按钮,因此您需要使用beforeinstallprompt event
。它不会触发也没关系,如果在已经安装PWA时触发,只会留下一个问题(我建议您在所有受支持的Android版本不同的浏览器上进行测试,如果您需要确定哪些不触发)
最后,假设beforeinstallprompt
事件被准确地触发,那么您是否应该准确地确定该应用是否已安装 >
答案 1 :(得分:2)
您可以检查用户是否正在使用已安装的版本
但是正如您提到的,您将不知道他们是否正在使用浏览器版本,并且还安装了它
一个想法
如果不是独立的,并且beforefireprompt不会触发,那么您可以假定它已安装并且他们正在使用浏览器版本。
大多数情况下,如果安装了大多数人,则将使用该版本。
在您的代码中,检查窗口是否独立
if (window.matchMedia('(display-mode: standalone)').matches) {
// do things here
// set a variable to be used when calling something
// e.g. call Google Analytics to track standalone use
}