Make it installable
This glitch already contains the critical components required to make a Progressive Web App installable, including a very simple service worker and a web app manifest. It also has an install button that is hidden by default.
Listen for the beforeinstallprompt event #
When the browser fires the beforeinstallprompt
event, that's the indication that the Progressive Web App can be installed and an install button can be shown to the user. The beforeinstallprompt
event is fired when the PWA meets the installability criteria.
- Click Remix to Edit to make the project editable.
- Add a
beforeinstallprompt
event handler to thewindow
object. - Save the
event
as a global variable; we'll need it later to show the prompt. - Unhide the install button.
Code:
window.addEventListener('beforeinstallprompt', (event) => {
// Prevent the mini-infobar from appearing on mobile.
event.preventDefault();
console.log('👍', 'beforeinstallprompt', event);
// Stash the event so it can be triggered later.
window.deferredPrompt = event;
// Remove the 'hidden' class from the install button container.
divInstall.classList.toggle('hidden', false);
});
Handle the install button click #
To show the install prompt, call prompt()
on the saved beforeinstallprompt
event. Calling prompt()
is done in the install button click handler because prompt()
must be called from a user gesture.
- Add a click event handler for the install button.
- Call
prompt()
on the savedbeforeinstallprompt
event. - Log the results of the prompt.
- Set the saved
beforeinstallprompt
event to null. - Hide the install button.
Code:
butInstall.addEventListener('click', async () => {
console.log('👍', 'butInstall-clicked');
const promptEvent = window.deferredPrompt;
if (!promptEvent) {
// The deferred prompt isn't available.
return;
}
// Show the install prompt.
promptEvent.prompt();
// Log the result
const result = await promptEvent.userChoice;
console.log('👍', 'userChoice', result);
// Reset the deferred prompt variable, since
// prompt() can only be called once.
window.deferredPrompt = null;
// Hide the install button.
divInstall.classList.toggle('hidden', true);
});
Track the install event #
Installing a Progressive Web App through an install button is only one way users can install a PWA. They can also use Chrome's menu, the mini-infobar, and through an icon in the omnibox. You can track all of these ways of installation by listening for the appinstalled
event.
- Add an
appinstalled
event handler to thewindow
object. - Log the install event to analytics or other mechanism.
Code:
window.addEventListener('appinstalled', (event) => {
console.log('👍', 'appinstalled', event);
// Clear the deferredPrompt so it can be garbage collected
window.deferredPrompt = null;
});
Further reading #
Congratulations, you app is now installable!
Here are some additional things that you can do:
- Detect if your app is launched from the home screen
- Show the operating system's app install prompt instead