Nextjs với fcm được send bằng data không bằng notification
Do mình gửi fcm qua data nên cần 2 vấn đề cần xử lý là khi mở trang web và khi chưa mở trang web
Khi mở trang web onMessage : ta tạo 1 component : nextfcm\src\components\fcmlisten.tsx như sau :
"use client";
import { useEffect } from "react";
import { messaging } from "@/lib/firebase/firebaseConfig";
import { onMessage } from "firebase/messaging";
type CustomPayloadData = {
title: string;
body: string;
image: string;
url: string;
};
export default function FCMListener() {
useEffect(() => {
if (typeof window !== "undefined") {
onMessage(messaging, (payload) => {
console.log("[onMessage] foreground notification: ", payload);
const data = payload.data as CustomPayloadData;
const title = data.title || "Thông báo";
const body = data.body || "";
const image = data.image || "";
const url = data.url || "https:://truyenvideo.com";
if (Notification.permission === "granted") {
const notification = new Notification(title, {
body,
icon: "/icon.png",
image,
});
notification.onclick = (event) => {
event.preventDefault();
if (url) {
window.open(url, "_blank");
}
};
}
});
}
}, []);
return null;
}
Trong file : nextfcm\public\firebase-messaging-sw.js
// public/firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/10.12.1/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.12.1/firebase-messaging-compat.js");
firebase.initializeApp({
apiKey: "AIzaSyBumY1plcU2hEXhREyTTTFIYhbaTCBHYrY",
projectId: "truyenvideo-3eb09",
messagingSenderId: "22119134901",
appId: "1:22119134901:web:180e66a9a8c2d70c4230fc"
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
const { title, body, image, url } = payload.data;
const notificationTitle = title;
const notificationOptions = {
body,
icon: "/icon.png",
image: image || "",
data: { url: url || "/" },
};
// self.registration.showNotification(title, notificationOptions);
// const notificationTitle = payload.notification.title;
// const notificationOptions = {
// body: payload.notification.body,
// icon: "/icon.png", // Biểu tượng nhỏ
// image: payload.data.image || "", // Hình ảnh hiển thị lớn (nếu có)
// data: {
// url: payload.data?.url || "/", // để xử lý click nếu muốn
// },
// };
self.registration.showNotification(notificationTitle, notificationOptions);
});
// // Xử lý khi click vào notification (nếu có URL được gửi từ client)
// self.addEventListener("notificationclick", function (event) {
// event.notification.close();
// const targetUrl = event.notification.data?.url || "/";
// event.waitUntil(clients.openWindow(targetUrl));
// });
self.addEventListener("notificationclick", function (event) {
event.notification.close();
const urlToOpen = event.notification?.data?.url || event.notification?.data?.FCM_MSG?.data?.url;
// Nếu có URL thì mở tab
if (urlToOpen) {
event.waitUntil(
clients.matchAll({ type: "window", includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
if (client.url === urlToOpen && "focus" in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(urlToOpen);
}
})
);
}
});
Link download : https://drive.google.com/file/d/1jxn5973b-3IwOYzo6ljG0bb7F2081lti/view?usp=sharing