next-pwa icon indicating copy to clipboard operation
next-pwa copied to clipboard

Trigger install on button click in UI?

Open Lucasvo1 opened this issue 2 years ago • 2 comments

Is it possible to trigger the PWA installation process from a button inside the UI?

Lucasvo1 avatar Nov 09 '22 04:11 Lucasvo1

@Lucasvo1 it would only be for desktop browsers that support a PWA on desktop (Chrome and Edge), but yes. I've using something like this to show a banner if there is a prompt set and if it's a supported desktop browser:

export function useAddToHomescreenPrompt(): [IBeforeInstallPromptEvent | null, () => void] {
    const [prompt, setPrompt] = useState<IBeforeInstallPromptEvent | null>(null);

    const promptToInstall = async () => {
        if (prompt) {
            prompt.prompt();
            const { outcome } = await prompt.userChoice;
            // Optionally, send analytics event with outcome of user choice
            console.log(`User response to the install prompt: ${outcome}`);
            // We've used the prompt, and can't use it again, throw it away
            return outcome;
        }
        return Promise.reject(new Error('Tried installing before browser sent "beforeinstallprompt" event'));
    };

    useEffect(() => {
        console.log('add listner beforeinstallprompt');

        const ready = (e: IBeforeInstallPromptEvent) => {
            e.preventDefault();
            console.log('Set prompt!');

            setPrompt(e);
        };

        window.addEventListener('beforeinstallprompt', ready as any);

        return () => {
            window.removeEventListener('beforeinstallprompt', ready as any);
        };
    }, []);

    return [prompt, promptToInstall];
}

kellypacker avatar Nov 21 '22 20:11 kellypacker

@Lucasvo1 Why is this marked as bug? @kellypacker already added the requested information so I believe this issue can be closed,

best regards

JoelBonet avatar Mar 26 '23 08:03 JoelBonet