Skip to content

Instantly share code, notes, and snippets.

@yeknava
Created August 19, 2020 14:25
Show Gist options
  • Save yeknava/d182332da43d941ceb511f1f86534e2d to your computer and use it in GitHub Desktop.
Save yeknava/d182332da43d941ceb511f1f86534e2d to your computer and use it in GitHub Desktop.
pwa install
let deferredPrompt = null;
let installed = false;
let initiated = false;
export default {
init() {
initiated = true;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
deferredPrompt = e;
if (window.matchMedia('(display-mode: standalone)').matches) {
installed = true;
} else {
installed = false;
}
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome !== 'accepted') {
installed = false;
}
deferredPrompt = null;
});
});
window.addEventListener('appinstalled', () => {
installed = true;
});
},
isInstalled() {
return initiated && installed;
},
install() {
if (!installed) {
deferredPrompt.prompt();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment