angular - 如何在 Angular PWA 中拦截应用程序安装提示?
问题描述
我使用 Angular指南创建了一个 PWA 。我在拦截应用安装横幅时遇到问题。我正在使用此代码将其推迟到稍后的时间点:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
console.log("Intercepting the app install banner prompt");
setTimeout(function() {
deferredPrompt.prompt();
}, 20000);
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
我的清单文件:
{
"name": "TreadWill",
"short_name": "TreadWill",
"theme_color": "#2a3b3d",
"background_color": "#2a3b3d",
"display": "standalone",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "assets/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "assets/icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "assets/icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "assets/icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "assets/icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "assets/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "assets/icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "assets/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
当我在 localhost 中尝试此代码时,console.log 中包含的消息被记录下来,但 20 秒后,我收到错误消息:
Uncaught (in promise) DOMException
在这一行:
deferredPrompt.prompt();
当我托管代码并在移动设备上试用时,应用安装横幅会立即显示,而不是 20 秒后显示。
我已经尝试将此代码放在 index.html 文件本身中,在一个单独的 js 文件中并在 index.html 文件中调用它。创建服务并在 .ts 文件中包含几乎相似的代码。没有任何效果。尽管出于绝望我正在尝试 js 解决方案,但我更喜欢 Angular 解决方案来解决这个问题。理想情况下,我想将“beforeinstallprompt”事件捕获并存储在全局变量中,并在不同点提示该事件。
如何解决这个问题呢?
解决方案
您可能做得正确,但根据这篇文章: “无论您是否在 beforeinstallprompt 事件中使用 preventDefault(),
当站点满足添加到主屏幕的条件时,都会出现迷你信息栏。”
所以对我来说,它也立即显示出来。
Pete LePage (@petele) 是在 Twitter 上关注 A2HS 更新的好人。
这是我构建的添加到主屏幕 (A2HS) 测试仪。页面底部有指向源代码的链接。随意使用任何可能有用的东西。我最近没有将它更新到最新版本的 angular。但它应该仍然可以正常工作,因为它是基本代码。
https://a2hs.glitch.me
推荐阅读
- java - 当前可见屏幕的getGlobalVisibleRect
- azure - Azure 上应用服务的 VNET 集成?
- javascript - javascript 待办事项列表未向待办事项列表添加新条目
- kubernetes - Kubernetes 多区域部署
- python - 从 backtrader 中的 pandas 数据馈送中提取数据帧
- amazon-web-services - 使用预签名 URL 将文件上传到 Amazon S3 时出现 CORS 错误
- regex - 在 Gatsby GraphQL 正则表达式过滤器中转义单词字符选择器
- c++ - 关于模板类中别名声明的问题
- python - PyQt5 - 在新窗口中打开 QMediaplayer 并播放视频
- c++ - 在 OpenGL 动画中限制 fovy