shadowwalker / next-pwa

Zero config PWA plugin for Next.js, with workbox 🧰
MIT License
3.86k stars 323 forks source link

Trigger install on button click in UI? #430

Open Lucasvo1 opened 1 year ago

Lucasvo1 commented 1 year ago

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

kellypacker commented 1 year ago

@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];
}
JoelBonet commented 1 year ago

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

best regards