Skip to content

Instantly share code, notes, and snippets.

@yaroschiffelers
Created July 25, 2018 09:13
Show Gist options
  • Select an option

  • Save yaroschiffelers/ec8418367d716e5b89ea4b9769243f76 to your computer and use it in GitHub Desktop.

Select an option

Save yaroschiffelers/ec8418367d716e5b89ea4b9769243f76 to your computer and use it in GitHub Desktop.

Revisions

  1. yaroschiffelers created this gist Jul 25, 2018.
    40 changes: 40 additions & 0 deletions Add-to-home-screen-Chrome.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    /**
    * Add To Home Screen Chrome 68+
    *
    * Changes to Add to Home Screen Behavior has the full details, including code samples you can use and more:
    * https://developers.google.com/web/updates/2018/06/a2hs-updates
    *
    * Credit: https://developers.google.com/web/updates/2018/07/nic68#a2hs
    * Add to home screen app criteria: https://developers.google.com/web/fundamentals/app-install-banners/#criteria
    */

    /**
    * If your site meets the add to home screen criteria, Chrome will no longer show the add to home screen banner.
    * Instead, you’re in control over when and how to prompt the user.
    *
    * To prompt the user, listen for the beforeinstallprompt event, then, save the event
    * and add a button or other UI element to your app to indicate it can be installed.
    */
    let installPromptEvent;

    window.addEventListener('beforeinstallprompt', (event) => {
    // Prevent Chrome <= 67 from automatically showing the prompt
    event.preventDefault();
    // Stash the event so it can be triggered later.
    installPromptEvent = event;
    // Update the install UI to notify the user app can be installed
    document.querySelector('#install-button').disabled = false;
    });

    /**
    * When the user clicks the install button, call prompt() on the saved beforeinstallprompt event,
    * Chrome then shows the add to home screen dialog.
    */
    btnInstall.addEventListener('click', () => {
    // Update the install UI to remove the install button
    document.querySelector('#install-button').disabled = true;
    // Show the modal add to home screen dialog
    installPromptEvent.prompt();
    // Wait for the user to respond to the prompt
    installPromptEvent.userChoice.then(handleInstall);
    });