Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a installable PWA using vuejs?

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?

Error

like image 984
Alex Hunter Avatar asked Feb 02 '21 00:02

Alex Hunter


1 Answers

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.

like image 51
PeteLe Avatar answered Sep 28 '22 05:09

PeteLe