amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

adding-custom-install-button-in-progressive-web-apps/ #78

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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/

Octagon-simon commented 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

bilelz commented 1 year ago

thanks! you did a better howto than https://web.dev/customize-install/

amitmerchant1990 commented 1 year ago

@bilelz glad you found it helpful!

bilelz commented 1 year ago

@amitmerchant1990 pushed here https://bilelz.dev/ :D