Open utterances-bot opened 1 year ago
Great article, thanks!
However you can set the value of deferred prompt to null
instead of leaving it as undefined
.
This is because you checked if the value was null
on your other block of code.
Leaving it unassigned gives it a default of undefined and it throws this error when the event is not assigned to the variable
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prompt')
Here's the complete code for people using react. Just place it in a new file pwa.js
within your public folder and link it in your index.html
let deferredPrompt = null;
window.addEventListener('beforeinstallprompt', (e) => {
//if app can be installed, assign the event to deferred prompt variable
deferredPrompt = e;
});
window.addEventListener('load', () => {
//select the button with ID pwaAppInstallBtn
const pwaAppInstallBtn = document.querySelector('#pwaAppInstallBtn');
pwaAppInstallBtn..addEventListener('click', async () => {
if (deferredPrompt !== null) {
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
if (outcome === 'accepted') {
deferredPrompt = null;
}
} else {
console.log("deferred prompt is null [Website cannot be installed]")
}
});
})
I hope this helps someone
thanks! you did a better howto than https://web.dev/customize-install/
@bilelz glad you found it helpful!
@amitmerchant1990 pushed here https://bilelz.dev/ :D
Really cool article ! The only thing that it may lack on is just a section to explain how to hide the "Install" button in the PWA itself after installing it
And fortunately that's super easy to do, you just need to implement something similar to this snippet of code:
const pwaMediaQuery = window.matchMedia("(display-mode: standalone)");
pwaMediaQuery.addEventListener("change", (e) => {
console.log("pwaMediaQuery", e);
// Call functions to hide the PWA banner and reset the deferred prompt
hidePwaBanner();
resetDeferredPrompt();
});
@LePhenix47 This section already takes care of that: https://www.amitmerchant.com/adding-custom-install-button-in-progressive-web-apps/#showing-install-button-only-in-supported-browsers
Adding a custom Install button in Progressive Web Apps — Amit Merchant — A blog on PHP, JavaScript, and more
The other day, I was looking for a way to add a custom “Install” button in my Notepad app which is essentially a Progressive Web App (PWA).
https://www.amitmerchant.com/adding-custom-install-button-in-progressive-web-apps/