通知打开
您可以通过将以下内容添加到您的 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 来自: