Display a prompt to install your PWA

Even if you have prepared a website to be a PWA (Progressive Web App) by enabling all the required features and settings, your user still has no way of knowing this option is available. To inform them, you can display a message on your website indicating they can now install your web app on any device. This message will appear only on devices that haven't installed the application yet.

There are several techniques to perform this process, in this example, we're going to explain how the javascript method BeforeInstallPromptEvent.prompt() is used to check the system, verify if your application is available, and in case it is not installed, display a prompt inviting the user to install it on their device, the message showed would be very similar to this one:

This method cannot be used directly and needs to first resolve the BeforeInstallPromptEvent event that verifies the presence of your application in the system. So we start by including a listener to determine if the PWA application is installed locally:

var beforeInstallPrompt = null;
window.addEventListener("beforeinstallprompt", eventHandler, errorHandler); function eventHandler(event){     beforeInstallPrompt = event;         } function errorHandler(e){     console.log('error: ' + e); }

Also, the browser requires some user interaction before displaying the message to avoid spamming applications that try to apply automatically. In this case, we will use a button in the HTML that invokes the install() function.

<button id="installBtn" onclick="install()" disabled > 
    Install PWA 

This button has intentionally enabled the "disabled" option by default. The intention here is that if your application is already installed, the button will display as disabled. To modify the button, we will update the eventHandler() method to remove that attribute and re-enable the button only if necessary.

function eventHandler(event){
    beforeInstallPrompt = event;

Finally, we include the method that is invoked from the button, which invites the user to install the PWA.

function install() {
    if (beforeInstallEvent) beforeInstallPrompt.prompt();

The full version of the code would look like this:

See the Pen Untitled by carlos (@carlosSolisModyo) on CodePen.

Important Notes:

  • For this code to work, you must have a working PWA.
  • Remember that beforeinstallprompt is an event that only works when the PWA is not installed in the system. If you install the app to test, remember to delete it to execute the code again.
  • For better results test in Google Chrome browser

Photo by Rodion Kutsaev on Unsplash.


Carlos Solis

Carlos Solis