Is it possible to create a button using vanilla Javascript inside my Progressive Web App that works the same as the add to home screen button?
For example my button would say "click to add this App to your device" when clicked the pwa would be added to the home screen of the device.
You can listen to the beforeinstallprompt event and then show a button on your template as described here.
Your code might be like the following:
window.addEventListener('beforeinstallprompt', (e) => {
// You can save the event in order to trigger the prompt later (see below)
deferredPrompt = e;
// Update UI notify the user they can add to home screen.
// With this you can show the Add to home screen button.
showInstallPromotion();
});
If you then want to show the A2HS (Add To Home Screen) dialog, you can invoke the prompt() method:
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
I wrote a series of articles about Progressive Web Apps, if you are interested in learning more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With