<html><head> <title>Test</title> <linkrel="manifest"href="manifest.json"></head><body> <p> If the <code>beforeinstallprompt</code> event fires, there will be a button displayed allowing you to use <code>prompt()</code> on the deferred event. </p> <buttonhidden>Show Prompt</button> <script>if ('serviceWorker'in navigator) {navigator.serviceWorker.register('sw.js');window.addEventListener('beforeinstallprompt', event => {event.preventDefault();var button =document.querySelector('button');button.removeAttribute('hidden');button.addEventListener('click', () => {event.prompt();button.setAttribute('disabled',true); }); }); } </script></body></html>
For a PWA to be installable, you need a registered service worker and a manifest file with the relevant fields.
You also need to attach a click event to an element in the HTML file. I added a button tag as the last element of my HTML file and set the display to none in CSS. Note: The button element is empty.
You listen for the beforeinstallprompt event and save the event to a variable. Then attach an event listener to your HTML element and listen for the click event. You also pass in a callback function to the event listener that calls prompt() on the saved event. Prompt displays a dialogue box. Using the User choice property you capture the user's action. User choice is a property that returns the users choice. If the users choice equates to accepted the installation begins else the dialog box is closed. You can only call prompt() on the deferred event once. Lastly, you set the deferred event to null.