DEV Community

Zoryana Vakh
Zoryana Vakh

Posted on

A2HS: How to add the PWA to Home Screen

Let's assume that you have the Progressive Web App (PWA).
One of the advantages of such the applications is the possibility to add it to home screen (A2HS).

More info about PWA here:

Chrome even prompts users to add the Progressive Web App to their home screen, when the Progressive Web App criteria are met.

But you can customize the behaviour.

For example, you need to add the banner with the "Install app" button. When the users click on it, the prompt shows up asking if they want to add the app to home screen. And when the users accept it, the app is added to home screen.

So, what allows you to customize it?
Let’s take a look at some important browser events:

Events

And how you can make use of it

A. Add the event listener on beforeinstallprompt event

window.addEventListener('beforeinstallprompt', function(event) {
  // not show the default browser install app prompt
  event.preventDefault();

  // add the banner here or make it visible
  // …

  // save the event to use it later
  // (it has the important prompt method and userChoice property)
  window.promptEvent = event;
});

B. Add the event listener on the banner’s button click

document.addEventListener('click', function(event) {
  if (event.target.matches('.install-button-class-name')) {
    addToHomeScreen();
  }
});

C. Add to Home Screen

function addToHomeScreen() {
  // show the install app prompt
  window.promptEvent.prompt();

  // handle the Decline/Accept choice of the user
  window.promptEvent.userChoice.then(function(choiceResult) {
    // hide the prompt banner here
    // …

    if (choiceResult.outcome === 'accepted') {
      console.info('mm User accepted the A2HS prompt');
    } else {
      console.info('mm User dismissed the A2HS prompt');
    }

    window.promptEvent = null;
  });

}

The important thing here is that the beforeinstallprompt event will not fire if the app has already been installed.
So, you don’t need to worry if the banner is present in that case.
You can also read the answer from https://stackoverflow.com/questions/50762626/pwa-beforeinstallprompt-not-called.
It will fire as usual after uninstalling the app.

The list of resources:

Top comments (0)