我使用 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”事件捕获并存储在全局变量中,并在不同点提示该事件。
如何解决这个问题呢?