import { getAnalytics } from "firebase/analytics";
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import imag from "../logo.svg";
const firebaseConfig = {
apiKey: "AIzaSyBelr-jMpWr1jF20fzRGTNLq6qas5_sgtE",
authDomain: "memo-track.firebaseapp.com",
projectId: "memo-track",
storageBucket: "memo-track.firebasestorage.app",
messagingSenderId: "715157154250",
appId: "1:715157154250:web:d22b5b79eb91a358928733",
measurementId: "G-SS779ZYXC3"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
const analytics = getAnalytics(app);
/**
* Get or generate the Firebase Cloud Messaging (FCM) token for the client.
*/
export const getOrGenerateFcmToken = async () => {
try {
const permission = await Notification.requestPermission();
console.log("Notification permission:", permission);
if (permission !== "granted") return null;
const token = await getToken(messaging, {
vapidKey: "BKQj51TqtH-h-COq1-R8QUvVNQHp3PSy6VZ6QVJne2qsnobkai2-nXejbNkn0dO6CGkZF3WHsQSu0D2qU_H31-s",
});
if (!token) return null;
const oldToken = localStorage.getItem("fcm_token");
if (oldToken !== token) {
console.log("New FCM token:", token);
localStorage.setItem("fcm_token", token);
} else {
console.log("Reusing old FCM token:", token);
}
return token;
} catch (err) {
console.error("Error retrieving FCM token:", err);
return null;
}
};
/**
* Sets up a foreground listener for incoming FCM messages.
*/
onMessage(messaging, (payload) => {
console.log("Foreground message received:", payload);
const title = payload.data?.title || payload.notification?.title || "New Notification";
const body = payload.data?.body || payload.notification?.body || "";
const icon = imag || "/firebase-logo.png";
if (Notification.permission === "granted") {
const notification = new Notification(title, { body, icon });
notification.onclick = () => {
console.log("Notification clicked:", payload);
const memoId = payload.data?.memo_id || payload.notification?.memo_id;
if (memoId) {
// Redirect to the memo details page when the notification is clicked
const url = `/memo/${memoId}`;
window.location.href = url;
}
};
}
});
Source