如何将数据从 Service Worker 传递到 React 应用程序?

问题描述

我正在使用 FCM(Firebase 云消息传递)。因此,如果我的应用程序选项卡没有获得焦点,我必须在名为 firebase-messaging-sw.js 的服务工作线程中接收通知。现在我想将数据从 service worker 传递给 react 组件。我搜索了很多,但没有在互联网上找到合适的教程。我使用 indexedDB 来存储通知数据,但我必须重新加载页面才能显示数据。提前致谢。

这是 firebase 消息服务工作者存储接收到的数据的代码

const createDBAndAddtoDb = (notification) => {
  const finalNotification = {
    notificationId: Math.floor(1 + Math.random() * 100),...notification,};

  let request = indexedDB.open("fcmDB");

  request.onupgradeneeded = (e) => {
    console.log("upgrade");
    const db = e.target.result;
    db.createObjectStore("notification",{
      keyPath: "notificationId",});

    const tx = e.target.transaction;
    const store = tx.objectStore("notification");
    store.put(finalNotification);
    // addNotification()
  };

  request.onsuccess = (e) => {
    console.log("Success");
    const db = e.target.result;
    const tx = db.transaction("notification","readwrite");
    const store = tx.objectStore("notification");
    store.add(finalNotification);
  };

  request.onerror = (e) => {
    console.log("Err");
  };
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.onBackgroundMessage(function (payload) {
  console.log(
    "[firebase-messaging-sw.js] Received background message ",payload
  );

  createDBAndAddtoDb(payload.notification);
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...