How to dispatch event on Push receive using Workbox?

578 views Asked by At

I have a VueJS component where I listen for pushMessageEvent :

<template>
  <div>
    <VueBotUI
        :options="options"
        :is-open="isOpen"
        :bot-typing="botTyping"
        :input-disable="inputDisable"
        :messages="messages"
        @msg-send="onSend"

    ></VueBotUI>
  </div>

</template>
<script>
export default {
  components: {
    VueBotUI
  },
  data: function () {
    return {
      options: {botTitle: 'test',},
      user: {msg: null,},
      msgRegex: /^[a-zA-Z ]+$/,
      messages: []
    }
  },

  mounted() {
    document.addEventListener('pushMsgEvent', this.printPush);
  },
  beforeDestroy () {
    document.removeEventListener('pushMsgEvent', this.printPush);
  },
  methods: {
    printPush (e) {
      console.log(e)
      console.log("------------------")
      console.log(e.detail)
    },
  }
}
</script>

And I want to fire this pushMessageEvent when I get a Push event in my service-worker:

/* eslint-disable */
importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);

// Load all ENVERYWHERE enviroment variables
importScripts('./env-vars.js')

const PushMsgEvent = new CustomEvent('pushMsgEvent', { detail: null });

workbox.core.skipWaiting();
workbox.core.clientsClaim();

self.__WB_MANIFEST;

// Listen to push event
self.addEventListener("push", (event) => {
  if (event.data) {
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

    PushMsgEvent.detail = event.data.text();
    //document.dispatchEvent(PushMsgEvent);
  }
});

workbox.precaching.precacheAndRoute([]);

but I can't use document.dispatchEvent since I get document is not defined, is it a workaround to fire this event and catch it in my component ?

I have read about workbox-window but I can't figure out how to fire my event from the service-worker in order to catch it in the component

1

There are 1 answers

0
J.erome On

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)
    }
}