我使用Angular guidelines创建了一个PWA。我正面临拦截app安装横幅的问题。我正在使用此代码将其推迟到以后:
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'事件,并在不同点提示事件。
如何解决这个问题呢?
你可能正确地做到了,但根据this article: “当网站满足添加到主屏幕标准时,无论您是否在beforeinstallprompt事件上阻止了默认(),都会显示迷你信息栏。” 所以对我来说,它立即显示。
Pete LePage(@petele)是在Twitter上关注A2HS更新的好人。
这是我建立的添加到主屏幕(A2HS)测试仪。页面底部有源代码链接。随意使用任何可能有用的东西。我最近没有更新到最新版本的角度。但它应该仍然可以工作,因为它是基本代码。 https://a2hs.glitch.me
Mathias回答中提供的链接帮助我解决了这个问题。我只是添加了一些在答案中没有明确提到但可能对其他人有帮助的要点。