是否有一种方法可以将Firebase Cloud消息(FCM)发送的通知更新到Web应用程序,而不是创建新的应用程序



我正在使用FCM进行聊天应用。每次用户收到消息时,我都会通过FCM向他发送通知。如果用户不在前景中使用我的Web应用程序,则会在默认服务工作者中发生消息处理,该服务器会在请求正文上指定的参数生成通知。问题是,每次发送新的推送消息时,该应用在后台时,浏览器(在Chrome和Firefox上进行了测试(都在创建一条新消息,而不是更新现有消息。我想保留已经可见的通知并仅更新其值,这是可能的吗?

如果应用不在前景中,则处理推送的服务工作者:

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();

发送到FCM服务器的请求的JSON主体

{
    "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
    }
}

好的,所以我发现了它显示了JSON主体可用的所有选项。对于我需要的东西,我只需要在JSON主体中的通知OBJ上添加"标签"参数即可。如果要更新通知,请使用相同的标签发送。示例:

{
    "notification": {
        "title": "",
        "body": "",
        "click_action": "",
        "icon": "",
        "tag" : "this must be the same for the notifications you want to update"
    },
    "to": "****",
    "data": {}
    }
}

在某些情况下,您可能需要替换通知来通知用户而不是默默更新。聊天应用程序就是一个很好的例子。在这种情况下,您应该将tagrenotify设置为true。

在您的sw.js

上写下此代码
    const title = 'Notification 2 of 2';
    const options = {
      tag: 'renotify',
      renotify: true
    };
    registration.showNotification(title, options);

您可以通过单击renotify按钮

在此处测试演示

最新更新