我已经编写了一个代码段,以将PWA Web应用程序添加到主屏幕(A2HS)。该代码运行良好。问题是,一旦我将PWA添加到主屏幕,第二次在浏览器的错误控制台中收到错误“无法安装站点:应用程序已安装”的错误。即使删除了桌面或主屏幕快捷方式,该错误也会弹出。 1.如何避免出现此错误? 2.如何根据开发和测试的要求重新显示A2HS?
<script type="text/javascript">
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
var tra2hs = document.getElementById('tra2hs');
var deferredPrompt;
$('#tra2hs').hide();
window.addEventListener('beforeinstallprompt', function(e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
$('#tra2hs').show();
});
// Installation must be done by a user gesture! Here, the button click
tra2hs.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
if(deferredPrompt)
{
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
$('#tra2hs').hide();
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
}
});
</script>