Capturing the Install Event
You'll learn how to intercept and save the browser's install prompt so you can show it at a time that makes sense for your users.
Why Capture the Install Event?
By default, browsers decide when to show the "Add to Home Screen" prompt for your PWA. This might happen at an inconvenient moment—like when a user just landed on your page. Instead, you can capture the beforeinstallprompt event and store it, giving you control over the timing. Show the prompt after users have engaged with your app and understand its value.
How It Works
When the browser determines your PWA is installable, it fires the beforeinstallprompt event. By listening for this event and calling preventDefault() on it, you stop the browser's default behavior. Then you save the event object in a variable for later use:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent the default mini-infobar from appearing
e.preventDefault();
// Stash the event so it can be triggered later
deferredPrompt = e;
// Now you can show your custom install button
showInstallButton();
});
Later, when the user clicks your custom install button (maybe after completing a task or expressing interest), you call deferredPrompt.prompt() to trigger the install dialog.
Think of It Like a Waiter
Imagine a waiter who approaches your table the moment you sit down, before you've even looked at the menu. Annoying, right? Capturing the install event is like telling the waiter "I'll call you when I'm ready to order"—then signaling them at the perfect moment.
Key Takeaway: Capturing the beforeinstallprompt event with preventDefault() and storing it lets you defer the install prompt until users are ready, improving conversion rates and user experience.