Firebase: Service messaging is not available

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
        );
      }
    })
  );
});

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật