PWA: preventDefault not working with beforeinstallprompt

Viewed 2712

I am testing on Chrome 70 on an Android device which should perfectly well prevent the AddToHomescreen prompt from showing. I cannot prevent the prompt or capture for later use. The prompt continues to show on every page load.

The textbox is filled and shows that the beforeinstallprompt event is loading. preventDefault on the event handler is not preventing the prompt.

Why??????

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="theme-color" content="#eaa103">
    <link rel="manifest" href="/pwa/manifest.json" />
    <title>Some App</title>
    <link rel="stylesheet" href="/pwa/css/bootstrap.min.css" />
    </head>
    <body>

    <div class="container">
        <testbox></testbox>
    </div>

    <script src="/pwa/js/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">

    </script>

    <script>
    var deferredPrompt;
    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;
        $("testbox").html("beforeinstallprompt loaded");
        return false;
    }); 
    </script>

    </body>
    </html>
2 Answers

According to this article from Google Developers: https://developers.google.com/web/updates/2018/06/a2hs-updates:

Starting Chrome 68 [...] the mini-infobar is shown regardless of if preventDefault() was called on the beforeinstallprompt event

So, there is currently no way for the developer to block the banner on the page on mobile Chrome version > 67 (it works on Desktop and on older mobile versions < 68).

There is a bit more info here: https://developers.google.com/web/fundamentals/app-install-banners/. As stated:

The mini-infobar is an interim experience for Chrome on Android

If dismissed by a user, it will not be shown until a sufficient period of time (~3 months) has passed.

I hope this helps.

Most probably Window is undefined because your page is rendering on the server-side.

solution: check before triggering an event or make sure your code is running on the client-side by running the script on runtime.

if you are using React or Nextjs, use the useEffect hook or componentDidMount.

Related