I need to get notifications from Firebase, but I’m facing a problem and I can’t find any answer for it:
Uncaught Error: Service messaging is not available
Package.json:
{
"name": "sookler",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@date-io/date-fns": "^2.17.0",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.0",
"@googlemaps/react-wrapper": "^1.1.35",
"@hookform/resolvers": "^3.3.1",
"@lottiefiles/react-lottie-player": "^3.5.4",
"@mui/icons-material": "^5.14.1",
"@mui/lab": "5.0.0-alpha.137",
"@mui/material": "^5.14.2",
"@mui/styled-engine-sc": "^5.12.0",
"@mui/styles": "^5.14.1",
"@mui/x-data-grid": "^6.10.2",
"@mui/x-date-pickers": "^6.10.2",
"@react-oauth/google": "^0.11.1",
"@reduxjs/toolkit": "^1.9.5",
"axios": "^1.4.0",
"compressorjs": "^1.2.1",
"date-fns": "^2.30.0",
"firebase": "^9.23.0",
"form-data": "^4.0.0",
"framer-motion": "^10.15.0",
"google-maps-react": "^2.0.6",
"i18next": "^23.4.1",
"leaflet": "^1.9.4",
"moment": "^2.30.1",
"mui-one-time-password-input": "^1.2.5",
"react": "^18.2.0",
"react-custom-scrollbars": "^4.2.1",
"react-dom": "^18.2.0",
"react-helmet": "^6.1.0",
"react-helmet-async": "^1.3.0",
"react-hook-form": "^7.45.2",
"react-i18next": "^13.0.3",
"react-leaflet": "^4.2.1",
"react-redux": "^8.1.2",
"react-responsive-carousel": "^3.2.23",
"react-router-dom": "^6.14.2",
"react-toastify": "^9.1.3",
"react-verification-code-input": "^1.2.9",
"styled-components": "^6.0.5",
"swiper": "^8.4.7",
"yup": "^1.2.0"
},
"devDependencies": {
"@types/leaflet": "^1.9.8",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react": "^4.0.3",
"typescript": "^5.0.2",
"vite": "^4.4.5"
}
}
firebaseInit.js:
import "firebase/compat/messaging";
import firebase from "firebase/compat/app";
const firebaseConfig = {
apiKey: "AIzaSyCSVOuA-4DT-NGyFXZ5IG13Q7gLpFoMa6Q",
authDomain: "sookler-plus-a1ef1.firebaseapp.com",
projectId: "sookler-plus-a1ef1",
storageBucket: "sookler-plus-a1ef1.appspot.com",
messagingSenderId: "868289122853",
appId: "1:868289122853:web:803612b64dcb557e04e5cc",
measurementId: "G-53P05PKSY1"
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
const publicKey = "BG-qtMNhGMcses3C612MtjKQZ9cbonJMI6pbQ4ec47jxtAjaQHepQvL45cANy_18B3I1xRP5WEi7mMvbCc3EnW0";
export const getFirebaseToken = async () => {
let currentToken = null;
try {
currentToken = await messaging.getToken({ vapidKey: publicKey });
} catch (error) {
console.error("An error occurred while retrieving token. ", error);
}
return currentToken;
};
export const onMessageListener = () =>
new Promise((resolve) => {
messaging.onMessage((payload) => {
resolve(payload);
});
});
firebase-messaging-sw.js:
/* eslint-disable no-undef */
// Scripts for firebase and firebase messaging
importScripts(
"xxx://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js"
);
importScripts(
"xxx://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js"
);
console.log("Firebase service worker script loaded");
const firebaseConfig = {
apiKey: "AIzaSyCSVOuA-4DT-NGyFXZ5IG13Q7gLpFoMa6Q",
authDomain: "sookler-plus-a1ef1.firebaseapp.com",
projectId: "sookler-plus-a1ef1",
storageBucket: "sookler-plus-a1ef1.appspot.com",
messagingSenderId: "868289122853",
appId: "1:868289122853:web:803612b64dcb557e04e5cc",
measurementId: "G-53P05PKSY1"
};
// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
self.addEventListener("notificationclick", function (event) {
event.notification.close();
const openWindowPromise = clients.openWindow("xxx://localhost:5173"); // Fill in the URL 'notifications page' to open, ex: xxx://XXX.com/my-notifications
event.waitUntil(openWindowPromise);
});
self.addEventListener("push", function (event) {
debugger;
console.log('eventeee: ', event)
const payload = event.data.json();
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "./favicon.ico", // Fill in the path to the icon
sound: "PATH_TO_SOUND", // Fill in the path to the sound file
dir: "auto",
};
// Check if any clients are currently visible (app is open)
const areClientsVisible = clients
.matchAll({
type: "window",
includeUncontrolled: true,
})
.then(function (clientList) {
for (let i = 0; i < clientList.length; i++) {
if (clientList[i].visibilityState === "visible") {
return true; // At least one client is visible
}
}
return false; // No visible clients
});
// Close any existing notifications
self.registration.getNotifications().then(function (notifications) {
console.log('notifications: ', notifications)
notifications.forEach(function (notification) {
notification.close();
});
});
// Show the notification only if no clients are visible
event.waitUntil(
areClientsVisible.then(function (visible) {
if (!visible) {
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
}
})
);
});