Having trouble capturing the 'notificationclick' event in the service worker when using Firebase messaging with Nuxt.js and Vue.js?

Experiencing difficulties in detecting events other than install, activate, or push in my firebase-messaging-sw.js. Notifications are being received and displayed, but I am unable to detect the event handler for notificationclick. When a firebase notification is clicked on, the notificationclick event does not show up in the service worker logs.

I am utilizing @nuxtjs/firebase 8.2.2 and have followed the setup instructions provided in the guide: .

In firebase-messaging-sw.js

self.addEventListener('notificationclick', function (event) {
  console.log('Notification click');
  event.notification.close();
  const url = 'home';
  event.waitUntil(
    self.clients.matchAll({ type: 'window' }).then((windowClients) => {
      // Check if there is already a window/tab open with the target URL
      for (let i = 0; i < windowClients.length; i++) {
        const client = windowClients[i];
        // If so, just focus it.
        if (client.url === url && 'focus' in client) {
          console.log('focusing..');
          return client.focus();
        }
      }
      if (self.clients.openWindow) {
        console.log('open window');
      }
    })
  );
}, false);

I am also attempting to utilize postMessage() to communicate with our service worker from a separate page to inject the user's email:

In account.vue

    navigator.serviceWorker.ready.then((sw) => {
      console.log('Requesting permission. Service worker: ', sw);
      Notification.requestPermission().then(async (permission) => {
        let token = null;
        if (permission === 'granted') {
          console.log('Notification permission granted.');
          await sw.active.postMessage({ action: 'saveEmail', email: this.email });
        }
      });
    });

In firebase-messaging-sw.js

self.addEventListener('message', async (msg) => {
  console.log('message', msg);
  const clients = await self.clients.matchAll({ type: 'window' });
  for (const client of clients) {
    client.postMessage(msg);
  }

  if (msg.data.action === 'saveEmail') {
    USER_EMAIL = msg.data.email;
  }
});

TLDR; Facing issues in monitoring notificationclick events in my firebase-messaging-sw.js.

EDIT: Added the push event handler which is functional, however, still struggling to capture the notificationclick event

Answer №1

Upon examining the importScripts used in my firebase-messaging-sw.js file, I came across a crucial section:

export async function handleNotificationClick(
  event: NotificationEvent
): Promise<void> {
  const payload: MessagePayloadInternal =
    event.notification?.data?.[FCM_MSG];

  if (!payload) {
    return;
  } else if (event.action) {
    // Handling action button clicks
    return;
  }

  // Stopping event propagation to other listeners
  event.stopImmediatePropagation();
  event.notification.close();

The line

event.stopImmediatePropagation();
was preventing my notificationclick listener from receiving the event. To resolve this issue, I moved my listener above the importScripts.

Regarding the postMessage problem, it stemmed from communication with another active service worker. Using getRegistrations(), I specified the targeted service worker for communication.

 navigator.serviceWorker.getRegistration('service-worker-scope-url').then((registration) => {
      console.log('Identified our service worker!');
      if (registration) {
        registration.active.postMessage({ action: 'saveEmail', email: this.$auth.user.email });
      }
    });

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

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

What could be causing my directive to not display my scope?

I am currently developing a directive that includes a custom controller, and I am testing the scope functionality. However, I am facing an issue where the ng-show directive is not functioning as expected when trying to test if the directive has a scope fro ...

Avoid Refreshing the Page When Pressing the Like Button

I've been working on code for liking a post and saving the value to a database using server-side code. However, I'm running into some issues when the page refreshes after clicking the like button. I tried using event.preventDefault() in my JavaSc ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

What is the best way to display multiple modals in a React app?

I am facing a challenge where I need to render multiple modals based on the number of items in the 'audios' property of an object. Currently, I am using the mui modal library for this functionality. Here are the variables being utilized: const ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...

Splitting the "pages" vendor file in @vue/cli 3: A step-by-step guide

After exploring the topic of "Building the app in multi-page mode" in the Vue Cli documentation, I found that there is only one vendor file instead of two per page entry. This made me realize that having a single large vendor file shared across multiple pa ...

Implementing the "@use" directive for "sass:math" within a Vue component

In my Nuxt 2 project, I have designed a custom button component with the following CSS style: <style lang="scss"> .my-button { // Implementing various styles and effects here $height: 28px; height: $height; border-radius: ...

Every time I attempt to load the table, I encounter an error

Encountering errors when attempting to load the table: 'Uncaught ReferenceError: usersArray is not defined at loadUsers (trgames.js:20:17) at trgames.js:22:1' and 'Uncaught TypeError: Cannot set properties of null (setting ...

Generating hyperlink regions dynamically

I am looking to create an image with a link map that will contain multiple areas that need to be updated frequently. Instead of constantly recreating the areas every few seconds, I want to generate them only when the user clicks on the image. I initially ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

How to manage ajax URLs across multiple pages?

I have my website set up at http://example.com/foo/ within a directory, separate from the main domain. Through the use of .htaccess, I've configured the URLs to appear as http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com ...

What is the definition of XLLS?

Is there a connection between the "XLLS" expression and AJAX / Javascript? What is the actual meaning of XLLS? Thank you in advance. including text from a comment in response ...when I searched for an answer on Google, all I found was Excel XLLs but no ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

Disable default styling on <v-card-actions>

Currently utilizing Vuetify, here is a simple setup for a <v-card> component: <template> <v-card> <v-card-title>MyCard</v-card-title> <v-card-text></v-card-text> <v-card-actions> <v-btn ...

Find the nth element of an array using Javascript's map function

Recently, I took on the challenge of learning Javascript independently and came across a rather complex task. I have an array with 18 labels and another 1D array containing all the values. Each label index corresponds to every nth element in the array. F ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

What is the best location to insert Google Search description in a VUE application?

We have successfully created a Vue application that supports multiple languages by utilizing i18n dictionaries. In addition, we have included descriptions in the "/public/index.html" file for Google search page visibility using meta tags: <meta proper ...

Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react' import { Stack, Typography } from '@mui/material' import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker' import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers&ap ...