Search code examples
javascriptreactjsprogressive-web-appsangular-pwa

Check if browser supports installing PWA


How can I check if a user's browser supports installing PWA?

I'm now trying to add this to a React application, but I want to know for other frameworks as well.

I've visited the documentation, but I'm trying to know how I (as the Front-end dev) can check if the user can install the app as PWA.

The best thing I could come up with is this:

const hasSupportForPWA = () => {
   if ('onbeforeinstallprompt' in window) {
      return true;
   }
   return false;
}

Is there a more elegant solution ?


Solution

  • Not the best answer, but maybe will help someone...

    So I ended up doing this (in Typescript):

       const checkIfCanInstallPWA():Promise<false| Event> {
         return new Promise((resolve, _reject) => {
            const timeout = setTimeout(() => {
                resolve(false);
            }, 1000);
    
            window.addEventListener('beforeinstallprompt', 
                (_event) => {
                _event.preventDefault();
                clearTimeout(timeout);
                resolve(_event);
            });
          })
        }
    

    And then when you need the logic\prompt the installation:

      // the logic, inside a component etc.
      const installationEvent: false| Event  = await checkIfCanInstallPWA();
      if (!installationEvent) {
         // can't install PWA
         // do stuff like hide the button... 
      } else {
          somePersistantStae.installationEvent = installationEvent;
      }
    

    Then when you want the user to get the installation prompt:

       // when the user clicks the install button
       const clickInstall = () => somePersistantStae.installationEvent.prompt()
      
    

    It's not pretty, I know...

    Conclusions:

    1. The beforeinstallprompt event fires if the browser is "willing" to install this PWA. Why this PWA? because for example in chrome, it won't install if the splash icon is not a perfect square or its size is smaller than 144x144px. So, the browser might not support installation of PWA in general, or might not want to install your specific PWA (this is still experimental as you can see here. So the "falsie" answer could come from a number of different reasons.
    2. If the browser "is willing" to install, The event object can be used even after several minutes (to my surprise)
    3. Even though it's a hacky solution its the only one that gave me the ability to place the install button somewhere in my app, and have the users install the PWA whenever they want (and not prompt them on the first page load, which is annoying IMO).