FCM onMessage event fails to activate

After extensively searching through numerous posts, I have been unsuccessful in achieving my goal with version 9.6.1

I receive a notification on my Windows notification bar. My objective is to log the message in the console and then take action based on it.

Requirement: When a message is sent to the client using the token from the server, that specific client should receive the data and based on that data, I intend to display a custom popup/modal. Can this be done using FCM?

Below is the configuration I set up on a page.

<script type="module">
        // Import the necessary functions from the required SDKs
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
        import {getToken,onMessage} from "https://www.gstatic.com/firebasejs/9.6.1/firebase-messaging.js";
        import {getMessaging,onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-messaging-sw.js";
        console.log(Notification.permission);
        if (Notification.permission == 'granted') {
            loadFCM();
        }
        function loadFCM(p){
            console.log(p);
            // TODO: Add SDKs for Firebase products that you want to use
            // Your web app's Firebase configuration
            // For Firebase JS SDK v7.20.0 and later, measurementId is optional
            const firebaseConfig = {
            apiKey: "esdfdsgdsg",
            authDomain: "sdgsdgsdg",
            projectId: "sgsdgsdgds",
            storageBucket: "sgdsgdsgds",
            messagingSenderId: "sdgdsgsdg",
            appId: "1:sgdgs:web:sgdgdsg",
            measurementId: "G-sgdgdsdg"
            };
            // Initialize Firebase
            const app = initializeApp(firebaseConfig);
            const messaging = getMessaging(app);
            console.log(messaging);
            getToken(messaging, { vapidKey: 'sdgdsgsd-sdgdgsdggds' }).then((currentToken) => {
                if (currentToken) {
                    console.log('token to send...'+currentToken);
                } else {
                    // Show permission request UI
                    console.log('No registration token available. Request permission to generate one.');
                }
                }).catch((err) => {
                console.log('An error occurred while retrieving token. ', err);
            });
            onMessage(messaging, (payload) => {
                console.log('Message received. ', payload);
                messaging.setBackgroundMessageHandler(payload => {
                    console.log(payload);
                    const title = payload.data.title;
                    const options = {
                        body: payload.data.score
                    };
                    return self.registration.showNotification(title, options);
                });
            });
            onBackgroundMessage(messaging, (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'
                };
                self.registration.showNotification(notificationTitle, notificationOptions);
            });
            
        }

      </script>

Using Postman, I made the following request. Can someone help me identify what I might be doing wrong?

  URL POST : https://fcm.googleapis.com/fcm/send
    {
        "data": {
            "title": "test",
            "body": "test",
        "click_action": "http://localhost:8001/"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://domain.in"
      }
    },
    "notification":{  
    "title":"mytitle",
    "body":"mybody",
    "content_available": true   },
    "to": "dMNS-tergdrgd-PPMcqiCseoE3fLIQYAL9KbCxlnKcN2yQ1VV" }

Answer №1

One issue arises when your notification is formatted in a specific way, like this:

{
    "notification": {  
        "title": "mytitle",
        "body": "mybody",
        "content_available": true 
    }  
}

In this case, the system treats it as a notification and onMessage function is not triggered.

To solve this, only send your data under the data key.

When using Postman, try sending the following instead :

URL POST : https://fcm.googleapis.com/fcm/send
{
    "data": {
        "title": "test",
        "body": "test",
        "click_action": "http://localhost:8001/"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://domain.in"
      }
    },
    "to": "dMNS-tergdrgd-PPMcqiCseoE3fLIQYAL9KbCxlnKcN2yQ1VV" 
}

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

Setting the height of the Angular UI modal relative to the height of the window

I am currently working on a modal that contains a significant amount of text. My main goal is to limit the height of the modal to the size of the window, while also adding a scrollbar to the content area positioned above the OK button. Check out the Plunk ...

Tips for fixing the "Uncaught TypeError: Cannot access property 'get' of undefined" error in Vue.JS 2

Here is my component: methods: { reloadMessage() { setTimeout(function () { this.$http.get(window.BaseUrl + '/message/inbox'); }, 1500); } } And here are my routes: Route::group(['prefix' => &ap ...

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

Is it common for browsers to continuously store compiled versions of script elements in their cache?

When using a web application that allows users to interact with javascript, they are required to include a function main() in their "program". The interface includes a "run" button and an "edit" button. Clicking the "run" button executes text from a <te ...

Upon clicking the button, the system triggers an update to the database

I am currently working on an interface that involves buttons for updating a database. For example, I have a variable named "Estado" which is initially set as "emAvaliacao". When the button "Aceite" is clicked, the value of "Estado" changes to "Aceite". Th ...

Flipping the order of elements in an array using JavaScript as described in the

While I am aware there are simpler methods to reverse arrays in JavaScript, I am seeking assistance to fully understand how this particular reverse method works. Your help in clarifying this is greatly appreciated. function reverseArrayInPlace(array) ...

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

I'm having issues with the functionality of my code inside the ng-template and ngIf. What could be

I am facing an issue with my method that is supposed to display the specified HTML content. However, it seems like the ngIf condition within the code block is not functioning correctly. Can someone help me understand why the ngIf statement is being ignored ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

Struggling with ajax: Converting a JavaScript variable to a PHP variable

I'm trying to convert a JavaScript variable into a PHP variable in order to use it in an SQL query, but for some reason it's not working as expected. Here is the HTML code: <select id = "dep_ID" name = "dep_ID" onchange="myFunction()"> A ...

The location.reload function keeps reloading repeatedly. It should only reload once when clicked

Is there a way to reload a specific div container without using ajax when the client requests it? I attempted to refresh the page with the following code: $('li.status-item a').click(function() { window.location.href=window.location.href; ...

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...

Stopping a Firefox addon with a button click: A step-by-step guide

Utilizing both the selection API and clipboard API, I have implemented a feature in my addon where data selected by the user is copied to the clipboard directly when a button is clicked (triggering the handleClick function). However, an issue arises when a ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

Enlarge the size of checkboxes on Phonegap for Android

I'm currently working on a quiz application using Phonegap, incorporating HTML, JavaScript, and CSS without any additional frameworks. My problem lies in the fact that the checkboxes appear too small on Android devices. I attempted to adjust the width ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...