【问题标题】:How to get push message events like click,close,show with firebase cloud messaging如何使用firebase云消息获取推送消息事件,如点击、关闭、显示
【发布时间】:2017-03-09 17:48:18
【问题描述】:

尝试使用 FCM 实现网络推送通知。

我可以使用 firebase 云消息库在浏览器上接收带有有效负载的推送消息。

下面是一个javascript代码sn-p。

<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js">  </script>
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.onMessage(function(payload){
    console.log('onMessage',payload);
});

如何捕捉点击、关闭、显示等事件?

【问题讨论】:

    标签: javascript firebase-cloud-messaging web-push


    【解决方案1】:

    通知打开

    您可以通过将以下内容添加到您的 firebase-messaging-sw.js 文件中来监听数据负载的通知点击:

    self.addEventListener('notificationclick', function(event) {
      event.notification.close();
    
      // Do something as the result of the notification click
    });
    

    通知关闭

    您可以通过以下方式监听通知关闭事件:

    self.addEventListener('notificationclose', function(event) {
      // Do something as the result of the notification close
    });
    

    注意:event.waitUntil()

    您应该知道,为确保您的代码有时间完成运行,您需要将一个 promise 传递给 event.waitUntil(),该承诺会在您的代码完成时解析,例如:

    self.addEventListener('notificationclick', function(event) {
      event.notification.close();
    
      const myPromise = new Promise(function(resolve, reject) {
        // Do you work here
    
        // Once finished, call resolve() or  reject().
        resolve();
      });
    
      event.waitUntil(myPromise);
    });
    

    如果通知是数据负载,您将知道何时显示通知,因为您需要在自己的代码中调用 self.registration.showNotification(),如下所示:

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

    您无法检测何时为“通知”有效负载显示通知,因为 SDK 会同时处理通知的显示和单击时的行为。

    代码 sn-ps 来自:

    【讨论】:

    • 当我使用 firebase 时如何在 2 秒后关闭通知?
    • 网络平台无法做到这一点。
    • self.addEventListener('notificationclick', function(event) {});当我点击通知时不会被调用。
    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多