I have developed PWA in my angular project, PWA install banner is showing up on the chrome browser by calling the prompt()
event like below,
this.promptEvent = event;
this.promptEvent.prompt();
but sometimes it is throwing an error
The prompt() method must be called with a user gesture.
I couldn't find a solution to this, any help would be appreciated.
Trigger prompt()
with a user action like a button click, don´t do it immediately after deferring the event.
var promptEvent;
// Capture event and defer
window.addEventListener('beforeinstallprompt', function (e) {
e.preventDefault();
promptEvent = e;
listenToUserAction();
});
// listen to install button clic
function listenToUserAction() {
const installBtn = document.querySelector(".install-btn");
installBtn.addEventListener("click", presentAddToHome);
}
// present install prompt to user
function presentAddToHome() {
promptEvent.prompt(); // Wait for the user to respond to the prompt
promptEvent.userChoice
.then(choice => {
if (choice.outcome === 'accepted') {
console.log('User accepted');
} else {
console.log('User dismissed');
}
})
}
Link to a complete tutorial https://love2dev.com/blog/beforeinstallprompt
Take note this will only work in SOME browsers https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent#Browser_compatibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With