Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The prompt() method must be called with a user gesture error in angular PWA

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.

like image 350
Siva Kumar S Avatar asked Sep 14 '25 16:09

Siva Kumar S


1 Answers

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

like image 82
guillefd Avatar answered Sep 17 '25 18:09

guillefd