Simultaneously, two identical messages arrived in the form of push notifications via FCM

I have been working on implementing WebPush notifications using Vue.js and FCM. However, when testing the functionality, I am facing an issue where instead of receiving just one notification from Firebase, TWO IDENTICAL PUSH NOTIFICATIONS are being received by the client, regardless of the browser or device.

Any assistance with resolving this problem would be greatly appreciated!

Here is a snippet of the JavaScript code:

const messaging = firebase.messaging();

function showNotification(data) {
    console.log(data);
    var title = data.notification.title;
    var tag = 'push';

    return self.registration.showNotification(title, {
        icon: data.notification.icon,
        body: data.notification.body,
        data: data.data,
        vibrate: [400,100,400],
        tag: tag
    });
}

self.addEventListener('install', (event) => {
    event.waitUntil(self.skipWaiting());
});

function receivePush(event) {

    console.log("receivePush");
    console.log(event.data.json());
    if(event.data) {
        data = event.data.json();
    }
    if('showNotification' in self.registration) {
        event.waitUntil(showNotification(data));
    }
}

function notificationClick(event) {
    event.notification.close();
    event.waitUntil(
        clients.openWindow(event.notification.data.url)
    );
    addClickCount(event.notification.data.record_id);
}

function addClickCount (record_id) {
    var api_url = 'https://' + location.host + '/_app/api/auth/push';
    fetch(api_url, {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'content-type': 'application/json',
        },
        body: JSON.stringify({id: record_id}),
    })
    .then(response => response.text())
    .then(text => console.log(text));
}

self.addEventListener('push', receivePush, false);
self.addEventListener('notificationclick', notificationClick, false);

And here is a snippet related to the token:

<template>
        <div class="column-btn">
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-yes"
                style="background:none"
                >Yes</a
              >
            </div>
          </div>
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-no"
                style="background:none"
                >No</a
              >
            </div>
          </div>
</template>

export default {
  methods: {
  },
  mounted() {
    var pData = this.$parent;
    var thisData = this;
    $(document).on('click', '.push-yes', function() {
      pData.permission_off();
      thisData.modalClose();
    });
    $(document).on('click', '.push-no', function() {
      thisData.modalClose();
    });
  },
};

Answer №1

FCM provides a clear set of instructions on how to incorporate code into the Service Worker firebase-messaging-sw.js file. You can find these steps at this link.

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

I followed these instructions and successfully implemented the code as directed.

Answer №2

return self.registration.showNotification(title, {
    icon: data.notification.icon,
    body: data.notification.body,
    vibrate: [400,100,400],
    tag: tag
});

If you are in backgroundMessage, make sure to remove the line 'self.registration.showNotification' to avoid sending the notification twice.

Visit this link for more information about notifications and data messages

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

Tips for avoiding divs from overlapping when the window size is modified

When I maximize the browser, everything aligns perfectly as planned. However, resizing the window causes my divs to overlap. Despite trying several similar posts on this issue without success, I have decided to share my own code. CODE: $(document).read ...

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit and I have a controller that combines both the view and edit functionalities: ... if ($routeParams.id) { $scope.itemId = $routeParams.id; $scope.editMode = true; Item.getB ...

Is it possible to pass arguments to setTimeout function?

At the current moment, my code looks like this: function showGrowl(lastNumber) { var num = lastNumber; //keep generating a random number untill it is not the same as the lastNumber used while((num = Math.ceil(Math.random() * 3)) == lastNumber); ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Can someone explain the purpose of this code snippet: `const { foo = "bar" } = "baz"`?

I came across this code not too long ago and had trouble finding the answer online, so I'm turning to you for help. The specific code snippet is from a webpack configuration file: const { NODE_ENV = 'production', } = process.env; Appreci ...

Transfer information using beforeEnter to navigate through route components

How can I pass data from a function called with beforeEnter to the corresponding route component(s)? The goal of using beforeEnter in this scenario is to validate the presence of a valid bearer token as a cookie. Currently, my beforeEnter function intera ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

Hide the menu when a menu link is selected

After conducting extensive research, I have come across several scripts that can achieve what I am trying to do. However, I am unsure of how to implement them with my particular WordPress theme. Therefore, I am seeking assistance here: The theme I am usin ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

Populate a Dropdown Menu with Directory Content for User Selection of d3.js JSON Data

I have a d3 forced-directed graph that is currently using a static JSON file for data: d3.json("../Data/sample.json", function(error, graph) { //do stuff }); However, I would like to give the user the ability to select the data file from a drop-down ...

A guide to selecting the bookmark with a URL that is on a currently opened page

To gain a clearer understanding of my goal, follow these steps: Open the Chrome Browser and go to a URL, such as https://www.google.com. Once the page loads, locate and click on the bookmark labeled "ABC", which contains the URL ({window.open('/ ...

Loop through the AJAX response containing JSON data

Need assistance in extracting specific information from each hotel key and its rates within this JSON structure using JavaScript: [ { "auditData": { "processTime": "1545", "timestamp": "2016-04-08 04:33:17.145", ...

Dayjs is failing to update when used in a Vue v-for loop

Within a component template lies the following code snippet: <v-col cols="6" v-for="(value, idx) in data[workingYear].monthValues" :key="idx"> {{ idx }} <v-row class="ai-center"> <!-- Month --& ...

The preflight request for CORS failed the access control check due to not receiving an HTTP ok status

How can I resolve this issue? Backend: ASP .Net Web APP - API, IIS Frontend: Vue Error: https://i.stack.imgur.com/QG1Yw.png https://i.stack.imgur.com/3tKh7.png Fiddler: https://i.stack.imgur.com/diN08.jpg web.config: <httpProtocol> <cus ...

What is the best way to extract the singular PDF link from a webpage?

Currently, I am attempting to utilize Selenium in Java to access DOM elements. However, I have encountered an issue while testing the code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is n ...

Adding a custom validation function to the joi.any() method - the easy way!

Is there a way to enhance joi.any() with a new rule that can be applied to any existing type, such as joi.boolean() or joi.string()? I already know how to extend joi by creating a custom type but that doesn't allow me to combine the new type with exis ...

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Is there a way to determine if a JavaScript method is compatible with my current Node.js version?

Looking to implement the reduce() method in my Node.js application, but I'm unsure if it's compatible with my current version 4.2.6. Is there a way to safely determine if I can use this method without causing any issues? Appreciate any help on t ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...