Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to update a notification sent by Firebase Cloud Message (FCM) to an web app instead of creating a new one?

I'm using FCM for a chat app. Everytime an user receives a message, I send him a notification via FCM. If user isn't with my web app in foreground, the message handling happens in a default Service Worker that generates a notification with the parameters I've specified on the body of my request. The problem is, everytime a new push message is sent and the app is in background, browsers (tested on Chrome and Firefox) are creating a new message instead of updating the existing one. I would like to keep the already visible notification and only update its value, is that possible?

Service Worker that handles the push if app isn't in foreground:

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': '*****'
});

const messaging = firebase.messaging();

JSON body of the request sent to FCM server

{
    "priority" : "normal",
    "collapse_key": "demo",
    "notification": {
        "title": "Felicius Humble",
        "body": "This is a sample message content",
        "click_action": "https://****.herokuapp.com",
        "icon": "****"
    },
    "to": "****",
    "data": {
        "id": 7,
        "timestamp": 1493573846692,
        "content": "teste",
        "type": "MESSAGE",
        "direction": "OUTPUT",
        "sender": {
            "id": 5,
            "name": "Felicius Humble",
            "email": "****@gmail.com",
            "gender": "MALE",
            "picture": "****",
            "facebookID": "****",
            "fcmToken": "****",
            "accessToken": "****"
        },
        "chatID": 3
    }
}
like image 430
Humble Student Avatar asked Apr 30 '17 17:04

Humble Student


1 Answers

Ok, so I've found this that shows all options available for the json body. For what I need I just need to add "tag" param on notification obj in my json body. If you want to update the notification, sent it with the same tag. Example:

{
    "notification": {
        "title": "",
        "body": "",
        "click_action": "",
        "icon": "",
        "tag" : "this must be the same for the notifications you want to update"
    },
    "to": "****",
    "data": {}
    }
}
like image 171
Humble Student Avatar answered Oct 12 '22 11:10

Humble Student