【问题标题】:Is there a way to update a notification sent by Firebase Cloud Message (FCM) to an web app instead of creating a new one?有没有办法更新 Firebase Cloud Messaging (FCM) 发送到 Web 应用程序的通知,而不是创建一个新通知?
【发布时间】:2017-09-28 07:17:52
【问题描述】:

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

在应用不在前台时处理推送的 Service Worker:

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

【问题讨论】:

    标签: firebase firebase-cloud-messaging


    【解决方案1】:

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

    将此代码写入您的sw.js

        const title = 'Notification 2 of 2';
        const options = {
          tag: 'renotify',
          renotify: true
        };
        registration.showNotification(title, options);
    

    您可以通过点击renotify 按钮在here 上测试演示

    【讨论】:

    【解决方案2】:

    好的,所以我找到了this,它显示了可用于 json 正文的所有选项。对于我需要的,我只需要在我的 json 正文中的通知 obj 上添加“标记”参数。 如果您想更新通知,请使用相同的标签发送。示例:

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

    【讨论】:

    • 很高兴听到您找到了相关文档。您能否在答案本身中包含最少的相关信息,而不仅仅是链接到文档(可能会随着时间而改变)?
    猜你喜欢
    • 2022-11-30
    • 2016-11-21
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2016-11-05
    • 2020-12-12
    相关资源
    最近更新 更多