4

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.

dns_nx
  • 3,651
  • 4
  • 37
  • 66
Siva Kumar S
  • 409
  • 1
  • 6
  • 21

1 Answers1

10

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

dns_nx
  • 3,651
  • 4
  • 37
  • 66
guillefd
  • 1,903
  • 1
  • 16
  • 26
  • 1
    This didn't help. I am calling the `prompt()` method on a button click but still getting the error. Here's my code: https://gist.github.com/murtuzaalisurti/785b2cb359bc7d996ebcc3539a67528b – murtuzaali_surti Apr 24 '23 at 10:58