Skip to Content

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <title>Add to Home Screen Example</title>

  <link rel="manifest" href="/manifest.webmanifest" />

</head>

<body>

  <button id="addToHomeBtn" style="display:none;">Add to Home Screen</button>


  <script>

    let deferredPrompt;

    const addBtn = document.getElementById('addToHomeBtn');


    window.addEventListener('beforeinstallprompt', (e) => {

      // Prevent the mini-infobar from appearing on mobile

      e.preventDefault();

      // Stash the event so it can be triggered later.

      deferredPrompt = e;

      // Update UI to notify the user they can add to home screen

      addBtn.style.display = 'block';


      addBtn.addEventListener('click', () => {

        // Show the prompt

        deferredPrompt.prompt();

        // Wait for the user to respond to the prompt

        deferredPrompt.userChoice.then((choiceResult) => {

          if (choiceResult.outcome === 'accepted') {

            console.log('User accepted the A2HS prompt');

          } else {

            console.log('User dismissed the A2HS prompt');

          }

          deferredPrompt = null;

          addBtn.style.display = 'none';

        });

      });

    });

  </script>

</body>

</html>