My lesson of the day. The browser in use: chrome
For a PWA to be installable, you need a registered service worker and a manifest file with the relevant fields.
You also need to attach a click event to an element in the HTML file. I added a button tag as the last element of my HTML file and set the display to none in CSS. Note: The button element is empty.
Next inline is the javascript code:
let defferedPrompt;
const addbtn = document.querySelector('.btn');
window.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
defferedPrompt = event
addbtn.style.display = 'block';
});
addbtn.addEventListener('click', event => {
defferedPrompt.prompt();
defferedPrompt.userChoice.then(choice => {
if(choice.outcome === 'accepted'){
console.log('user accepted the prompt')
}
defferedPrompt = null;
})
})
The code explained:
You listen for the beforeinstallprompt
event and save the event to a variable. Then attach an event listener to your HTML element and listen for the click event. You also pass in a callback function to the event listener that calls prompt()
on the saved event. Prompt displays a dialogue box. Using the User choice property you capture the user's action. User choice is a property that returns the users choice. If the users choice equates to accepted the installation begins else the dialog box is closed. You can only call prompt()
on the deferred event once. Lastly, you set the deferred event to null.
That's it for day 68
Lets do this again tomorrow
Top comments (4)
This tutorial is helpful if you're targeting Chrome users only. It might be helpful to add a disclaimer that the BeforeInstallPromptEvent API is experimental and has poor cross-browser support.
Thank you for the feedback, I'll make the necessary adjustments. It's not really a tutorial, just a documentation of what I'm learning on a day to day basis.
I'm not conversant with unity or gaming. But if your unity games are web based then you can provide a "native-mobile-applike-experince" by turning them into Progressive Web Apps. I hope that helps.
I'm just as curious are you are with PWA which is why I'm learning it. I am making it installable because I want to have and interact with the web app as an app on my phone: the essence of PWA.