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.
/**
* 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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment