Implementing event dispatch on Push notifications received with Workbox

In my VueJS component, I have set up a listener for the pushMessageEvent event:

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

I would like to trigger the pushMessageEvent when a Push event is received 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([]);

However, I am facing an issue with using document.dispatchEvent as it results in a document is not defined error. Is there a workaround to trigger this event and handle it in my component?

I have come across the workbox-window solution, but I am unsure how to dispatch the event from the service worker to be caught in the component.

Answer №1

Here is my solution:

Inside the service-worker.js file:

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

Within my component.vue file:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effective Strategies for Preserving Form Input Values during Validation Failure in Spring MVC

I am currently working on validating user input, and I want the user's input fields to be retained in case of any validation errors. This is how I have set up my input fields: <form:input path="firstName" class="text short" id="firstName" value=" ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

Why is my ASP.NET checkbox losing its value after postback because of a JavaScript/jQuery array?

I'm facing an issue with a simple asp:RadioButtonList nested inside a form tag where it's not retaining its value on postback. Here's the code snippet: <form runat="server"> <div class="Form"> <span class="FirstField"> ...

Using JQuery to dynamically set dropdown option values from a JSON object

I have an HTML code snippet: $.ajax({ type: "POST", url: "hanca/hanca_crud.php", dataType: 'json', data: { id_hanca: id_hanca, type: "detail_hanca" }, //detail_hanca success: function(data) { var teks = ""; $.each( ...

I'm baffled by why I keep receiving the error message "Unknown provider: $routeProvider <- $route <- AppController" in AngularJS, even though I have already

I've exhausted all the solutions I found on stackoverflow without success. Apologies if this is a duplicate question. My goal is to reset the content of my Bootstrap table with a button click using the function $route.reload(). However, when I includ ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

How to iterate through a JavaScript array in reverse order using a for loop and the array's length property

When looking to iterate through an array with the values [8,7,6,5,4], some may wonder why a for loop using the length of 5 continues to function even though there is no element at index 5 in the array. for(let i=array.length;i>=0;i++){ //do somethin ...

Using Vue.js to trigger mouseover or hover events within Element UI tabs

I need to display a tooltip when hovering over a tab in Vue.js. My tabs are functioning correctly, but I'm not sure how to implement a mouseover event on el-tab-pane? <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit ...

In order to comply with JSX syntax rules in Gatsby.js, it is necessary to enclose adjacent elements

I want to apologize beforehand for the code quality. Every time I attempt to insert my HTML code into the Gatsby.js project on the index.js page, I encounter this error: ERROR in ./src/components/section3.js Module build failed (from ./node_modules/gatsb ...

What could be causing ng-submit to not successfully transmit data?

I'm currently going through this Yeoman tutorial, but I'm encountering some issues. The new todo is not being added to the $scope.todos as expected, and I'm struggling to identify the reason behind it. You can access the code here: Upon c ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

Add characters to div using JavaScript

I am curious about which framework, if any, would be most effective for capturing keystrokes and adding them to an HTML element such as a "p" element. My goal is to allow the client to type something on the keyboard and have it immediately displayed in the ...

Using a class variable to access canvas methods in Javascript

As someone new to Javascript, I am facing a bit of confusion when it comes to classes and objects. Recently, I refactored some code into a working class but the process did not go as smoothly as I had hoped. Despite searching through Stackoverflow, Google ...

Expanding/Combining entities

I'm facing an issue while trying to Extend/Push/Merge an object using AngularJS. The problem arises when I attempt to extend the object, as it adds a new object with an Index of 0 and subsequent additions also receive the same index of 0. //Original ...

Manage over 200 checkboxes by storing them in the state

I am facing an issue with managing checkboxes within a table in my application. The table fetches user data and renders each row as its own component, with each row containing a checkbox. The goal is to enable the users to select checkboxes and retrieve t ...

Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below: https://i.sstatic.net/QeBhc.jpg M ...

Steps to dynamically display or conceal a DIV using Bootstrap 5

I am facing an issue with a navbar that has buttons to reveal hidden divs underneath. <a data-bs-toggle="offcanvas" href="#select" role="button" aria-controls="select"></a> <div id="select" c ...

Tips for navigating through complex JSON structures with JavaScript or JQuery

I'm currently navigating the complexities of parsing a multi-level JSON array as a newcomer to JSON. I am seeking solutions using either JavaScript or jQuery. My goal is to extract the application id, application description, and Product description f ...

The result from the AngularJs promise is coming back as undefined

I am facing an issue while trying to implement the login function of my AuthService factory in conjunction with my AuthLoginController controller. The problem arises when the User.login function is triggered with incorrect email and password details, causi ...