Display Button for installing "Web App" without using the Browser-Dialog

63 Views Asked by At

I use manifest.json on my website for installing the service as a "webapp". Normally, Android/Chrome-Users have to do the following steps to install the service:

  1. Click on the Menu-Icon
  2. Chose "Install App" from the dialog
  3. Confirm installation

Yesterday I visited a website with a nice button that was shown automatically for a few seconds:

Long story short: After clicking on the button the webapp was installed on my smartphone without the three steps mentioned. How can I create such a button/dialog?

1

There are 1 best solutions below

0
SeLeCtRa On

You can use beforeInstallPromptEvent.

NOTE: This is experimental. Works on all chromium browsers. Doesn't work on firefox and safari.

I researched before and found only this. Works flawless in chrome/edge.

You can use it like that: REACT EXAMPLE


After checking, if installation is allowed, which means you can prompt and user doesn't have it installed on phone/computer.


/**
 * The BeforeInstallPromptEvent is fired at the Window.onbeforeinstallprompt handler
 * before a user is prompted to "install" a web site to a home screen on mobile.
 *
 * This is an experimental technology. Be cautious when using it.
 *
 * @compatibility {@link https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent#Browser_compatibility}
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent}
 */
interface BeforeInstallPromptEvent extends Event {
  /**
   * Returns an array of DOMString items containing the platforms on which the event was dispatched.
   * This is provided for user agents that want to present a choice of versions to the user such as,
   * for example, "web" or "play" which would allow the user to chose between a web version or
   * an Android version.
   */
  readonly platforms?: Array<string>

  /**
   * Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed".
   */
  readonly userChoice?: Promise<{
    outcome: 'accepted' | 'dismissed'
    platform: string
  }>

  /**
   * Allows a developer to show the install prompt at a time of their own choosing.
   * This method returns a Promise.
   */
  prompt?(): Promise<void>
}

const [isInstallAllowed, setIsInstallAllowed] = useState<boolean | undefined>(undefined)

const [installEvent, setInstallEvent] = useState<BeforeInstallPromptEvent | null>(null)


const beforeAppInstallpromptHandler = (e: BeforeInstallPromptEvent) => {
  e.preventDefault()
  setIsInstallAllowed(true)
  setInstallEvent(e)
}


window.addEventListener('beforeinstallprompt', beforeAppInstallpromptHandler)