Skip to content

Instantly share code, notes, and snippets.

@moughamir
Last active February 6, 2021 22:50
Show Gist options
  • Save moughamir/b87d11e1cab4d415138ac4600f877369 to your computer and use it in GitHub Desktop.
Save moughamir/b87d11e1cab4d415138ac4600f877369 to your computer and use it in GitHub Desktop.
pwa-install-promt.js
<div class="prompt">
<p>Install the app in your device</p>
<button type="button" class="prompt__install">Yes Please</button>
<button type="button" class="prompt__close">No Thanks</button>
</div>
<style>
.prompt {
display: none;
}
</style>
const prompt = document.querySelector('.prompt');
const installButton = prompt.querySelector('.prompt__install');
const closeButton = prompt.querySelector('.prompt__close');
let installEvent;
function getVisited() {
return localStorage.getItem('install-prompt');
}
function setVisited() {
localStorage.setItem('install-prompt', true);
}
window.addEventListener('beforeinstallprompt', (event) => {
event.preventDefault();
if (!getVisited()) {
prompt.style.display = 'block';
installEvent = event;
}
})
installButton.addEventListener('click', () => {
prompt.style.display = 'none';
installEvent.prompt();
installEvent.userChoice.then((choice) => {
if (choice.outcome !== 'accepted') {
setVisited();
}
installEvent = null;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment