Jonathan Bennett

Chrome PWA Install Prompts

PWA

TLDR: jump to the code?

Chrome offers a fantastic new tool for helping your users install your web app called an install prompt.

Before jumping through the code, let’s go over the concept. If your app meets install criteria, the browser will fire on an event. This event has a single use callback which will actually trigger the install prompt for the user.

You will wait for this event and when it comes in you will save the event, and display an appropriate UI to request the install. If the user interacts with the UI, call the install callback. At that point you can do whatever you need to cleanup after yourself.

The Code

With the concept covered, what does the actual code look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let installPromptEvent = null
let ui = document.getElementById("my-install-button")

window.addEventListener("beforeinstallprompt", e => {
	e.preventDefault()
	installPromptEvent = e // save event for use later on
	
	ui.removeAttribute("hidden") // show your install UI
})

ui.addEventListener("click", e => {
	e.preventDefault()
	if (!installPromptEvent) return // exit if we got here without an installprompt event

	installPromptEvent.prompt()
	ui.setAttribute("hidden", "")
})
1
<button id="my-install-button" hidden>Please install me</button>

And that’s all there is to it. This is actually the easiest way to install an app on a mobile device, even easier than a native app! I am really hopeful that this (or something similar) comes to iOS too 🤞🏻