如何通过Firebase云消息传递获取推送消息事件,如点击、关闭和显示。

8
尝试使用FCM实现Web推送通知。
使用Firebase云消息传递库,我能够在浏览器上接收带有负载的推送消息。
以下是JavaScript代码片段。
<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);
});

如何捕获像点击、关闭、展示等事件?
1个回答

7

通知打开

您可以通过将以下内容添加到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(),当您的代码完成时该promise会被解决,例如:

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处理通知的显示和点击行为时,您无法检测“通知”负载的通知何时被显示。

代码片段来自:


1
当我使用Firebase时,如何在2秒后关闭通知? - Ketha Kavya
你不能使用网络平台完成这个任务。 - Matt Gaunt
当我点击通知时,self.addEventListener('notificationclick', function(event) {});没有被调用。 - Yash Kadiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接