Is it possible to make an in-app button that triggers the PWA "Add to Home Screen" install banner?

45,057

Solution 1

Thanks for all the great answers. Recently it appears that things have become more standardized, and there is a solid way of doing things in chrome at least that allows users to click and install the app even if they missed the prompt etc.

Pete LePage wrote a very clear article on web.dev called How to provide your own in-app install experience which details the process. The code snippets and process is taken directly from the article.

  1. Listen for the beforeinstallprompt event.
let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent the mini-infobar from appearing on mobile
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI notify the user they can install the PWA
  showInstallPromotion();
});
  1. Save the beforeinstallprompt event, so it can be used to trigger the install flow later.
buttonInstall.addEventListener('click', (e) => {
  // Hide the app provided install promotion
  hideMyInstallPromotion();
  // Show the install prompt
  deferredPrompt.prompt();
  // Wait for the user to respond to the prompt
  deferredPrompt.userChoice.then((choiceResult) => {
    if (choiceResult.outcome === 'accepted') {
      console.log('User accepted the install prompt');
    } else {
      console.log('User dismissed the install prompt');
    }
  });
});

  1. Alert the user that your PWA is installable, and provide a button or other element to start the in-app installation flow.

For more details and other capabilities, see the full article.

I made a working demo of a this process implemented in React. (source code)

Also, for a slightly different approach, you can see how the maker(s) of Snapdrop implemented an install button in the source code.

Solution 2

Chrome(or any PWA supporting browser) triggers the beforeinstallprompt event for Web app install banner, which you can catch and re-trigger in more appropriate time when you think user wont miss it/convinced about adding your site to home page. Starting Chrome version 68, catching beforeinstallprompt and handling the install prompt programmatically is mandatory and no banners will be shown automatically.

In case the user have missed the prompt/declined to add to home screen, the event can't be manually triggered by our code. This is intentionally left that way to avoid web pages annoying the users to repeatedly prompt the user for adding to home screen. Thinking of users perspective, this makes complete sense.

Yes, there are cases when user miss the option accidentally and he may not know of the browser menu option to "Add to home screen" and it would be nice for us to trigger the same again. But unfortunately, that's not an option. At lest for now and I personally don't see that changing much considering how developers can abuse if its left to the developers to prompt.

Alternate option: If the user have missed the install prompt or even chosen not to install it to home screen, give some time and when you think he is starting to like your site(based on conversions) you can show him a full page or half page Div popup kind of install instructions to add your site to home screen from browsers menu. It can have some images or Gif animation showing user how to add to home screen from the menu. With that, it should be self explanatory to most users, if not all.

Here is some code example for the same, which is iOS specific(look under #PROTIP 3).

As a bonus, you can show some promotions like discounts or added features when user add to home screen, which will convince user to do so. PWA has a way to find if the site is accessed form the home screen or browser.

For Development/testing: If you need this banner to come multiple times for dev/testing purpose, you can set the below flow in your Chrome for the same,

chrome://flags/#bypass-app-banner-engagement-checks

Solution 3

Well, there's nothing stopping you from storing the deferredPrompt value in a variable and use it later. Then you can popup a custom box, and if the user closes it down, you still haven't ran deferredPrompt.prompt() and can use it later. I store mine in Redux. If the user closes the install prompt, I use the deferredPrompt in the hamburger menu to install it at any time.

Listen to install and store event as prompt

 const beforeInstallListener = e => {
        // Prevent Chrome 76 and later from showing the install prompt
        e.preventDefault();
        // Stash the event so it can be triggered later.
        dispatch(setAndroidDeferredPrompt(e));
        dispatch(showAndroidPromptDownload(true));
    };
    window.addEventListener("beforeinstallprompt", beforeInstallListener);

Create a function which uses this deferredPrompt to prompt the user

    const installToAndroid = async () => {
    dispatch(showAndroidPromptDownload(false));
    deferredPrompt.prompt(); // Wait for the user to respond to the prompt
    const choiceResult = await deferredPrompt.userChoice;

    if (choiceResult.outcome === "accepted") {
        console.log("User accepted the PWA prompt");
    } else {
        closeAndroidPromptWithoutDownload();
        console.log("User dismissed the PWA prompt");
    }
    dispatch(setAndroidDeferredPrompt(null));
};

Remember, if the user clicks the banner to install, deferredPrompt.prompt() is invoked and it won't work anymore. Therefore I keep a check to see if deferredPrompt exists, and remember to set it to null if the user has invoked .prompt().

{deferredPrompt && <button onClick={() => installPWA(deferredPrompt)}>Installer til hjemskjerm</button>}

This was done with React Hooks, Redux and LocalStorage (where I store a pwa.reducer.js state)

Solution 4

In mobile Chrome on Android, "Add to Home Screen" can be accessed from the browser's menu. (Similar options may exist for mobile Safari/Firefox on Android/iOS as well.) The web app manifest file is read and the app is added as it would be with the original prompt feature.

While JavaScript cannot be used to manually invoke the prompt, a workaround would be to provide on-screen instructions showing users how to manually open the menu and add for their specific user-agent.

enter image description here

enter image description here

Solution 5

In Dev mode,

Try this in devtools console to trigger the event:

event = new Event('beforeinstallprompt')
window.dispatchEvent(event)
Share:
45,057

Related videos on Youtube

Adam D
Author by

Adam D

I love open source, collaboration, and thinking about how software can help language learning.

Updated on July 09, 2022

Comments

  • Adam D
    Adam D almost 2 years

    I understand that with a properly made Progressive Web App mobile browsers will display a banner prompting users to 'Install' the app on their home screen.

    I have been looking around for a way to trigger that prompt from within the app, but have not been able to find anything.

    Is there a line of JavaScript that can be used to call the install prompt banner at any time?? Something that I could add to a install button tucked away in a help screen for instance?

    It might be difficult for some users to find the "Add to Home Screen" option if they missed the install banner prompt. I'd like to give them a button they can click to be prompted again.

    2020 EDIT: Yes, this is possible in Chrome - see answer below

    See this great article: How to provide your own in-app install experience and my working demo of the article's process applied in a React app.

    Or for a slightly different approach, see how snapdrop.net did it.

    • Mathias Rechtzigel
      Mathias Rechtzigel almost 6 years
      What type of device are you using to test?
    • Mathias Rechtzigel
      Mathias Rechtzigel almost 6 years
      Here's some useful documentation that you may want to review: developers.google.com/web/fundamentals/app-install-banners
    • Adam D
      Adam D almost 6 years
      @MathiasRechtzigel Thank you, that's very useful. As this documentation and Anand's answer below explained, unfortunately it seem that it's not possible to do what I imagined, which was create a link to prompt an install at any time. The prompt only comes up once, whether naturally or caught and then released from a button press etc.
    • huykon225
      huykon225 almost 5 years
      any solution for only safari on iphone?
    • Weihang Jian
      Weihang Jian over 3 years
      No, it is not possible.
    • Adam D
      Adam D over 3 years
      As this great article from web.dev explains, this is totally possible now.
  • Pardeep Jain
    Pardeep Jain about 5 years
    May I know how would I know if user has already installed PWA on mobile or not?
  • Fabien Snauwaert
    Fabien Snauwaert over 4 years
    @PardeepJain If you set the start_url to something like /?utm_source=pwa, you should be able to check programmatically whether the user opened the app as a PWA (though not if it's installed but opened from a regular browser.)
  • xyres
    xyres over 4 years
    Browsers should give users the option to permanently disable a prompt. So if an app is abusing the prompt, users can disable it, and if a user missed the prompt, the app can still trigger it again. I think that's a nice balance.
  • Muhammad Usama Mashkoor
    Muhammad Usama Mashkoor over 4 years
    Hi, can you please share your redux code to I am facing the same scenario as you have implemented in react and redux.
  • Mackelito
    Mackelito over 4 years
    This is like the opposite of what the question is.. this is the manual way.. question is about triggering it thru code..
  • Mackelito
    Mackelito over 4 years
    It has not changed.. just pointed out that you answered something else
  • Anthony
    Anthony over 4 years
    What I'm looking for is a CSS built overlay when iOS is detected and the browser isn't already a PWA
  • Fabien Snauwaert
    Fabien Snauwaert over 4 years
    A way to check whether the user is using the standalone app: if (window.matchMedia('(display-mode: standalone)').matches) { … }. See docs
  • Hugolpz
    Hugolpz over 3 years
    Hi, please share an agnostic pwa install button example in pure js + css + htm. I still +1ed this answer ;)
  • Yatko
    Yatko about 3 years
    All seems to be in order while checked with Lighthouse but the prompt isn't triggered on Android/Chrome at cambio.express - any guess why? Thank you!
  • Anand
    Anand about 3 years
    @Yatko I could able to add to home screen manually and it's working as expected. But didn't get the prompt though. May be chrome didn't feel the site is significant enough user would want to install. There was some such criteria which is not very explicit on how chrome assess it. Will check lighthouse tomorrow to see if I find anything.
  • Yatko
    Yatko about 3 years
    @Anand makes great sense, offering to install every page that has a PWA functionality would trigger a horde of sites spamming us with "Install {app}" prompts. Most likely you are right, pages with low significance simply won't trigger the prompt. We were thinking about two other requirements: Fallback page and decent internet speed (we don't have the first and only have 3G in Cuba) ... if anyone can trigger the PWA install prompt, please let us know. Thank you!
  • Sean McCarthy
    Sean McCarthy over 2 years
    That's neat for firing the event, but doesn't actually create a prompt, or allow the install from the event