How to Use the berforeinstallprompt Event to Create a Custom PWA Add to Homescreen Experience

flipkart-homescreenOne of the bigger announcements made at Google I/O 2018 was the end of Chrome automatically prompting users to add Progressive Web Apps (PWA) to their home screen. This has probably gone unnoticed by many after being impressed with Google Duplex. But for business owners and developers this is big news and requires new thinking and coding for progressive web apps.

Now you are responsible to trigger a prompt to the user, not Chrome. But there is an event, beforeinstallprompt, you can intercept to create the prompt.

This is a big switch from the workflow Google has trained us to expect in recent years. But actually puts them more inline with the add to homescreen processes implemented by other browsers like FireFox and Samsung Internet.

Now instead of Chrome determining when to prompt the user, you controll when the user is prompted, it triggers the beforeinstallprompt event in the background.

You need to build a user experience triggered by the 'beforeinstallprompt' event. I will give you a simple example later in this post.

At first I thought this change was a step back. But the more I analyze the change I think this is for the better.

Chrome is the only browser that automatically prompts users to 'install' a PWA. Plus, Edge does not yet support an add to desktop or start menu feature.

This has caused me to look for a reasonable way to implement a good cross-browser prompt solution. In the past Mateo Spinnelli's AddToHomeScreen library worked for both iOS and Android web apps in the pre-PWA days. I think that can serve as a good model to follow in this situation.

It doesn't solve the complete problem because other browsers still don't have a formal add to homescreen prompt, just a process. This means you will still need to solve the cross-browser, corss-platform problem.

In a way, while Chrome is providing a nice, consistent UI solution, it is the only browser with this in place, which ironically makes things more difficult. But I think because it currently is the only browser supporting the beforeinstallprompt (to my knowledge) you have a solid way to manage a Chrome vs not-Chrome solution.

In this post I will give you a high level example of how you can build an add to homescreen prompt experience for your progressive web apps.

The New Add To Homescreen Flow

If the add to homescreen criteria are met the beforeinstallprompt event is triggered.

The criteria include the following:

  • The web app is not already installed
  • Meets a user engagement heuristic (currently, the user has interacted with the domain for at least 30 seconds)
  • Meets the Progressive Web App criteria:
    • Includes a web app manifest that includes:
      • short_name or name
      • icons including a 192px and a 512px version
      • start_url
    • Served over HTTPS (required for service workers)
    • Has registered a service worker with a fetch event handler

I want to note the fetch event handler cannot be a noop method, meaning it is just a placeholder. I shared last summer you just need a function, but that criteria is changing as the Chrome team evolves their feature detections.

Most of the criteria should be expected if you are familiar with progressive web apps.

The second requirement of 30 seconds of user engagement is a relative requirement. And this demonstrates how the add to homescreen prompt is a non-standard feature.

The 30 second time frame I suspect is arbitrary. And what qualifies as interacting with the domain is also subjective. I have not seen qualitative criteria as to what triggers this as a positive state yet.

The key for you to remember is capturing the beforeinstallprompt event and controlling the process.

  • Listen for the beforeinstallprompt event
  • Notify the user your app can be installed with a button or other element that will generate a user gesture event.
  • Show the prompt by calling prompt() on the saved beforeinstallprompt event.

The following code should be added to your site's JavaScript. For this demonstration I upgraded the 2048 game I announced a few months ago.


var deferredPrompt;

window.addEventListener('beforeinstallprompt', function (e) {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;

  showAddToHomeScreen();

});

The first thing you should do is create a variable outside the scope of the beforeinstallprompt event handler. This way you can reference it later. This handler saves a reference to the beforeinstallprompt event object. You can use this later to trigger the add to homescreen prompt on demand.

The next step is to call the showAddToHomeScreen method. This simply shows a message to the user about the application being elible to install.


function showAddToHomeScreen() {

  var a2hsBtn = document.querySelector(".ad2hs-prompt");

  a2hsBtn.style.display = "block";

  a2hsBtn.addEventListener("click", addToHomeScreen);

}

This just changes the notifications display state from none to block. Again this is an overly simple solution. For a real production application I would employ much better UX ;)

add-to-homescreen-notification

What you should take away from this step is how you are responsible for notifiying your customer they can add your PWA to their homescreen, or in the case of Windows 'install' the application.

If you have been paying attention to recommended prompting practices you should not brute force actions like asking for push notification, geo-location or other permission based actions. Add to homescreen is similar.

This approach makes the task less intrusive, which means you are more likely to get the engagement numbers you are after.

I made the message element live by binding a click event handler. When clicked or tapped, the addToHomeScreen method is triggered.


function addToHomeScreen() {

var a2hsBtn = document.querySelector(".ad2hs-prompt");

// hide our user interface that shows our A2HS button a2hsBtn.style.display = 'none';

// Show the prompt deferredPrompt.prompt();

// Wait for the user to respond to the prompt deferredPrompt.userChoice .then(function(choiceResult){

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

  deferredPrompt = null;

});

}

This will trigger the native Chrome add to homescreen banner. But first I hide the message because the user has responded to the message.

Next, I use the reference to the deferredPrompt to trigger the native prompt by calling the prompt method. The prompt method can only be called once, so don't think you can just keep bothering the visitor to add to their homescreen. Be nice!

When they respond to the prompt they can either install the PWA or chose not to. The deferredPrompt.userChoice returns a promise when this happens. It supplies a variable you can check the outcome property.

If the outcome was "accepted" you know they added or installed the PWA. Otherwise they chose not to. You can log this information to your analytics to determine what your response rates are, etc. Use those values to determine if you need to improve your user experience or not.

Start URL Displayed on Desktop PWA

beforeinstallprompt Is Not a Web Standard

Unlike service workers and the web manifest file the add to homescreen prompt is not a web standard. This means browsers are and always have been able to dictate how and if the user is prompted to add a progressive web app to the homescreen.

Most browsers have implemented subtle queues to the visitor, like an icon in the address bar. Others make it discoverable in the browser's menus.

Microsoft has not yet implemented an add to homescreen process of any sort. Instead they have invested their resources in ingesting PWAs in their App Store.

At last week's Build they started hinting at a possible UI icon to alert users a PWA can be added to the desktop.

Summary

If you have a progressive web app or are planning on upgrading to a PWA soon you need to be aware of this new workflow. Use the example code I provided here to get started. Remember this is just a simple example and I encourage you to get creative with your implementations.

Unfortunately this is a Chrome only feature, but you can utilize it as a potential model to reach users in other browsers. This process should be part of your application's onboarding experience.

The source code is available on GitHub and play the game at 2048.love2dev.com.

Share This Article With Your Friends!