React 的 Firebase 推送通知(后台通知)

问题描述 投票:0回答:1

我已将 Firebase 推送通知集成到我的 React 项目中,并成功接收前台和后台通知。但是,虽然我可以在 firebase-messaging-sw.js 文件中看到后台通知有效负载,但我无法在功能组件中接收它们。

这是我的 firebase-messaging-sw 文件的代码

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

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FCM_API_KEY,
  authDomain: process.env.REACT_APP_FCM_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FCM_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FCM_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FCM_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FCM_APP_ID,
  measurementId: process.env.REACT_APP_MEASUREMENT_ID,
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log(payload, "Received background message");

  const parseData = (data) => {
    try {
      return JSON.parse(data);
    } catch (err) {
      console.error("Failed to parse data:", err);
      return null;
    }
  };

  const parsedData = parseData(payload?.data?.payload);
  console.log(parsedData, "Parsed background message data");

  const notificationTitle = parsedData?.title || "New Notification";
  const notificationOptions = {
    body: parsedData?.message || "You have a new message.",
  };

  self.clients.matchAll().then((clients) => {
    if (clients.length === 0) {
      console.log("No clients found, showing notification.", parsedData);
      self.registration.showNotification(notificationTitle, notificationOptions);
    } else {
      clients.forEach((client) => {
        console.log("Posting message to client:", client);
        client.postMessage({
          msg: "background-notification",
          data: parsedData,
        });
      });
    }
  });
});

我还在我的 App.js 文件中注册了一个服务工作者,这是它的代码

 useEffect(() => {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker
      .register("/firebase-messaging-sw.js", { scope: "./conversation" })
      .then((registration) => {
        console.log("Service Worker registered successfully with scope:", registration.scope);
        return registration;
      })
      .catch((error) => {
        console.log("Service Worker registration failed:", error);
      });
  }
}, []);

在我的功能组件中我添加了这段代码

useEffect(() => {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.addEventListener("message", (event) => {
      if (event.data && event.data.msg === "background-notification") {
        console.log("Background notification received in component:", event.data.data);
        // setNotificationData(event.data.data);
      }
    });
  }
}, []);

无法运行 postMessage 服务,因为显示我的客户数组为空。

reactjs node.js firebase push-notification
1个回答
0
投票

辞职吧:)))))))))))))))))))))))

© www.soinside.com 2019 - 2024. All rights reserved.