【问题标题】:Catch FCM notification message in service worker after click_action triggered触发 click_action 后在服务人员中捕获 FCM 通知消息
【发布时间】:2021-06-28 18:34:20
【问题描述】:

我面临的通知消息的问题是,只要定义的 click_action 的完整 URL 与任何打开的选项卡都不匹配,就会打开一个新选项卡。

假设 click_action 等于 mydomain.com 并且打开了一个带有 URL mydomain.com/anyroute 的标签。由于 URL 不匹配,将打开一个新选项卡。但我希望已经打开的选项卡能够获得焦点,而不是打开一个新选项卡。

用户点击消息后,Service Worker 是否可以捕获到通知消息,还是有其他可能?

编辑:到目前为止,onBackgroundMessagenotificationclick 等服务人员的事件未通过,因为推送通知是 notification_message

【问题讨论】:

  • 您是使用 firebase sdk 进行推送通知,还是在 Service Worker 中为它们编写自己的处理程序?
  • 感谢您的留言!我使用 SDK

标签: firebase-cloud-messaging progressive-web-apps


【解决方案1】:

您可以使用on 解释here

messaging.onBackgroundMessage((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",
  };

  // Loop trough all clients controled by the SW
  self.clients.matchAll(options).then(function (clients) {
    // Let's see if we already have a chat window open:
    const url = new URL(client.url);

    if (url.pathname == "/custom_url/") {
      // Excellent, let's use it!
      client.focus();
    }

    // do something with your clients list
  });

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


您可以在哪里使用self.clients 循环通过由 SW 控制的应用程序的所有选项卡/客户端。如果 url/patch 匹配,您可以专注于特定客户端。

【讨论】:

  • 感谢您的建议。但不幸的是,由于消息类型notification_message,这个事件处理程序没有被传递。使用 data_message 类型,您的解决方案可能会起作用,但在这种情况下不会
猜你喜欢
  • 2022-08-15
  • 2021-02-09
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多