[Vuejs]-How to dispatch event on Push receive using Workbox?

0👍

My solution:

service-worker.js:

// Listen to push event
self.addEventListener("push", (event) => {
  if (event.data) {
    self.clients.matchAll().then(clients => {
      clients.forEach(client => {
        client.postMessage(JSON.stringify(event.data.text()));
      });
    });
  }
});

my component.vue :

mounted() {
    navigator.serviceWorker.addEventListener('message', event => {
      let msg = event.data;
      this.printPush(msg);
    });
  },
  beforeDestroy () {
    navigator.serviceWorker.removeEventListener('message', event => {
      this.printPush(event);
    });
  },
  methods: {
    printPush (e) {
      console.log(e)
    }
}

Leave a comment