Custom Install Button UI
You'll learn how to create a custom install button that gives you full control over when and how users are invited to install your Progressive Web App.
Why Custom Install Buttons Matter
By default, browsers show their own install prompts at times you can't control. A custom install button lets you choose the perfect moment—after a user has engaged with your app, completed a task, or during onboarding—to encourage installation. This increases conversion rates and provides a better user experience.
Building Your Custom UI
You've already captured the beforeinstallprompt event (from the previous lesson). Now you'll use that stored prompt to trigger installation when the user clicks your custom button:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
deferredPrompt = e;
// Show your custom install button
const installButton = document.getElementById('install-button');
installButton.style.display = 'block';
});
// Handle button click
document.getElementById('install-button').addEventListener('click', async () => {
if (!deferredPrompt) return;
// Trigger the install prompt
deferredPrompt.prompt();
// Wait for user's response
const { outcome } = await deferredPrompt.userChoice;
console.log(`User ${outcome} the install prompt`);
// Reset the deferred prompt
deferredPrompt = null;
// Hide the button
document.getElementById('install-button').style.display = 'none';
});
Think of it like holding a door open: the browser gives you the handle (deferredPrompt), but you decide when to invite someone through (prompt()).
Key Takeaway: Store the beforeinstallprompt event, show a custom button, and call prompt() on the deferred prompt when clicked—giving you complete control over your PWA's install experience.