使用 onBackgroundMessage() 时,Firebase 网络推送通知被触发两次

Wal*_*lla 7 push-notification firebase web-push firebase-cloud-messaging

我真的不知道这些东西是怎么回事。我正在为我的网站正常使用 FCM 网络推送。如果我在前台,我可以在网站上收到消息,如果我在后台,我会收到通知。到现在为止还挺好。

importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-messaging.js');

firebase.initializeApp({
  ...
});

const messaging = firebase.messaging();
Run Code Online (Sandbox Code Playgroud)

问题是 firebase-messaging-sw.js 的默认配置在显示 chrome 图标的背景中显示通知。我希望能够自定义此通知并显示我的应用程序图标。然后在网上阅读我发现我需要用onBackgroundMessage()来拦截消息。

importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.5/firebase-messaging.js');

firebase.initializeApp({
  ...
});

const messaging = firebase.messaging();

if (messaging) {
  messaging.onBackgroundMessage(payload => {
    const notificationTitle = payload.notification.title || payload.data.title;
    const notificationOptions = {
      body: payload.notification.body || payload.data.subtitle || '',
      icon: 'https://firebasestorage.googleapis.com/v0/b/yes-4-web.appspot.com/o/pontonos%2Ficons%2Fandroid-chrome-192x192.png?alt=media&token=35616a6b-5e70-43a0-9284-d780793fa076',
      data: payload.data
    };

    return self.registration.showNotification(notificationTitle, notificationOptions);
  });

  self.addEventListener('notificationclick', event => {
    event.notification.close();
    event.waitUntil(clients.matchAll({ type: "window" }).then(function(clientList) {
      for (let i = 0; i < clientList.length; i++) {
        const client = clientList[i];
        if (client.url === '/' && 'focus' in client) {
          if (event.notification.data.route) client.href(event.notification.data.route);
          return client.focus();
        }
      }
      if (clients.openWindow)
        return clients.openWindow(event.notification.data.route || '/');
    }));
  });
}
Run Code Online (Sandbox Code Playgroud)

问题是现在,当使用 onBackgroundMessage() 时,我会看到两个通知,一个是带有 chrome 图标的原始通知,另一个是带有我的应用程序图标的个性化消息(见图)

通知

另一个问题是,如果我点击原始通知,我的网站标签会成为主要焦点,但如果我点击个性化通知,我的网站会打开一个新标签。

Cor*_*ius 20

也许为时已晚。

我遇到了这个问题,正如我最终发现的那样,问题是我在有效负载中发送“通知”和“数据”对象。

删除“通知”并仅保留“数据”解决了问题。

来自 FCM 文档:

当您希望 FCM 代表您的客户端应用程序处理显示通知时,请使用通知消息。当您想要在客户端应用程序上处理消息时,请使用数据消息。

FCM 可以发送包括可选数据有效负载的通知消息。在这种情况下,FCM 处理显示通知负载,而客户端应用程序处理数据负载。

这是我的有效负载现在的样子:

$payload = [
            'message' => [
                'token' => $token,
                'data'  => $msg,
                //'notification'  => $msg, (this caused the notification to deliver twice)
                'webpush'=> [
                  'fcm_options'=> [
                    'link' => $link,
                    'analytics_label' => 'notification_label'
                  ]
                ]
            ],
        ];
Run Code Online (Sandbox Code Playgroud)

https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages


小智 11

如果您使用Firebase Admin发送消息,您可以在onBackgroundMessage中 console.log ,FCM 将发送如下所示的一些数据。

来自 firead 的有效负载

有效负载包含属性notification,来自FCM 文档

使用 FCM,您可以向客户端发送两种类型的消息:

通知消息,有时被认为是“显示消息”。这些由 FCM SDK 自动处理。

这意味着,如果您的数据具有属性,notification它将由 FCM 自动处理,您不需要添加方法来在onBackgroundMessage中显示通知。

如果您在onBackgroundMessage中添加显示通知的方法,则预计会显示两次,因为第一个 notif 由 FCM 自动处理,第二个由onBackgroundMessage.

如果您不希望 FCM 自动显示通知,则只需notification从有效负载中删除属性即可。

你可以试试这个:

//Insert to firebase-messaging-sw.js

firebase.initializeApp(firebaseConfig);


class CustomPushEvent extends Event {
  constructor(data) {
    super('push');

    Object.assign(this, data);
    this.custom = true;
  }
}

/*
 * Overrides push notification data, to avoid having 'notification' key and firebase blocking
 * the message handler from being called
 */
self.addEventListener('push', (e) => {
  // Skip if event is our own custom event
  if (e.custom) return;

  // Kep old event data to override
  const oldData = e.data;

  // Create a new event to dispatch, pull values from notification key and put it in data key,
  // and then remove notification key
  const newEvent = new CustomPushEvent({
    data: {
      ehheh: oldData.json(),
      json() {
        const newData = oldData.json();
        newData.data = {
          ...newData.data,
          ...newData.notification,
        };
        delete newData.notification;
        return newData;
      },
    },
    waitUntil: e.waitUntil.bind(e),
  });

  // Stop event propagation
  e.stopImmediatePropagation();

  // Dispatch the new wrapped event
  dispatchEvent(newEvent);
});
Run Code Online (Sandbox Code Playgroud)

源代码Github

上面的代码将属性中的 key 移动notificationdata,所以预期的结果将如下所示

在此输入图像描述

这样,FCM 将不会显示通知,因为有效负载没有 property notification