I want to make my vue app installable via chrome/firefox using a button (to show a pwa install prompt)
<button @click="install">install</button>
var deferredPrompt
methods: {
install() {
deferredPrompt.prompt()
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt')
} else {
console.log('User dismissed the A2HS prompt')
}
deferredPrompt = null
})
}
}
Once i build the app and its online, i click the button and got deferredPrompt null on console. What im missing?
It looks like you don't have a beforeinstallprompt
event listener on the window
object.
In vuejs, you'll need to do that in the created()
event, for example:
export default {
name: "App",
data() {
return {
deferredPrompt: null
};
},
created() {
window.addEventListener("beforeinstallprompt", (e) => {
e.preventDefault();
// Stash the event so it can be triggered later.
this.deferredPrompt = e;
});
},
methods: {
async install() {
this.deferredPrompt.prompt();
}
}
};
Also, you should only show the install button only when the beforeinstallprompt
event has been fired, and deferredPrompt
has been set. Otherwise, the button will be visible but not do anything.
Check out https://medium.com/js-dojo/promoting-your-vue-js-pwa-installation-6bd112342c19 for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With