当用户安装 pwa 时,下面的函数可以正常工作。但是,如果他们拒绝,下次他们访问该站点时,deferredPrompt.prompt(); 会抛出 Uncaught (in promise) DOMException 异常,即使 deferredPrompt.prompt(); 不是未定义的。
关于用户之前给出的答案,我需要检查什么吗?
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
//e.preventDefault();
let deferredPrompt;
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Show the prompt
deferredPrompt.prompt();
// 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;
});
});
最佳答案
我有类似的代码,遇到同样的问题。经过一些研究,我了解到 deferredPrompt.prompt() 将返回一个 userResponsePromise,这是一个 promise 。然后我尝试通过添加这行代码来观察日志,看看会发生什么。
deferredPrompt.prompt()
.then(res => console.log(res))
.catch(error => { console.log(`----> ${error}`) })
在控制台日志中,它显示
----> NotAllowedError: The prompt() method must be called with a user gesture
我猜A2HS安装过程可能不允许直接调用prompt()。
因此,我尝试通过设置调用操作按钮来更改我的代码,该按钮将调用 prompt() 方法,我认为它应该暗示日志所建议的“用户手势”的含义。
这是我的新代码,看起来像 Add to Home Screen tutorial from Google dev. 中的代码(不知道为什么第一时间没关注:P)
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault()
deferredPrompt = e
})
const btnInstallApp = document.getElementById('btn-install-app')
if(btnInstallApp) {
btnInstallApp.addEventListener('click', e => {
deferredPrompt.prompt()
deferredPrompt.userChoice
.then(choiceResult => {
if(choiceResult.outcome === 'accepted') {
console.log('user accepted A2HS prompt')
} else {
console.log('user dismissed A2HS prompt')
}
deferredPrompt = null
})
})
}
我在页面某处添加了我的安装应用程序按钮
<button id="btn-install-app" class="btn">Install App</button>
这次我可以在单击“安装应用程序”按钮后看到“添加到主屏幕”提示。 希望对您有所帮助。
关于javascript - PWA beforeinstallprompt Uncaught (in promise) DOMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56236591/