在 firebase 云消息传递应用程序中出现许多错误

Getting many errors in firebase cloud messaging app

更新: 包含整个代码的存储库如下: https://github.com/akash07k/Clouding 因此,我正在开发我的 FCM 应用程序,一旦我允许该应用程序的通知,我就会收到很多错误。 第一个错误是关于“onTokenRefresh”不是一个函数。 我对每条错误消息进行了很多搜索,但找不到任何线索。 如果有人可以帮助我,我将非常感激。 我在下面提供了错误和整个代码: 以下是错误:

(index):73 Uncaught ReferenceError: onTokenRefresh is not defined
    at initFirebaseMessagingRegistration ((index):73)
    at (index):31
(index):46 Got notification permission
(index):55 Didn't get notification permission TypeError: Cannot read properties of undefined (reading 'vapidKey')
    at updateVapidKey (updateVapidKey.ts:27)
    at getToken (getToken.ts:42)
    at getToken (api.ts:114)
    at (index):47
(index):65 Didn't get notification permission FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
    at registerDefaultSw (registerDefaultSw.ts:43)
    at async updateSwReg (updateSwReg.ts:28)
    at async getToken (getToken.ts:43)
Error
(index):73 Uncaught ReferenceError: onTokenRefresh is not defined
    at initFirebaseMessagingRegistration ((index):73)
    at (index):31
(index):46 Got notification permission
(index):55 Didn't get notification permission TypeError: Cannot read properties of undefined (reading 'vapidKey')
    at updateVapidKey (updateVapidKey.ts:27)
    at getToken (getToken.ts:42)
    at getToken (api.ts:114)
    at (index):47
Error
firebase-messaging-sw.js:4 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js' failed to load.
    at http://localhost:3000/firebase-messaging-sw.js:4:1
(index):65 Didn't get notification permission FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
    at registerDefaultSw (registerDefaultSw.ts:43)
    at async updateSwReg (updateSwReg.ts:28)
    at async getToken (getToken.ts:43)

代码: index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clouding</title>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
        import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries

        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
            apiKey: "AIzaSyDOVN1qOGzsD6AI-2jA05LpfQIJ5aoCuD4",
            authDomain: "clouding-aa740.firebaseapp.com",
            projectId: "clouding-aa740",
            storageBucket: "clouding-aa740.appspot.com",
            messagingSenderId: "1059589787087",
            appId: "1:1059589787087:web:cdd636057d2a921ccdd6ba",
            measurementId: "G-CD2BEK39LZ"
        };
        window.addEventListener("click", (e) => {
            switch (e.target.id) {
                case "btnPermissions":
                    initFirebaseMessagingRegistration();
                    break;
            }
        });
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        //        const analytics = getAnalytics(app);
        const messaging = getMessaging(app);


        function initFirebaseMessagingRegistration() {

            Notification.requestPermission()
                .then(function () {
                    messageElement.innerHTML = "Got notification permission";
                    console.log("Got notification permission");
                    return getToken();
                })
                .then(function (token) {
                    // print the token on the HTML page
                    tokenElement.innerHTML = "Token is " + token;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            // Don't forget your vapidKey here
            getToken(messaging, { vapidKey: "293kfk" })
                .then((t) => {
                    tokenElement.innerHTML = "Token is " + r;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            onMessage(messaging, (payload) => {
                console.log("Message received. ", JSON.stringify(payload));
                notificationElement.innerHTML =
                    notificationElement.innerHTML + " " + payload.data.notification;
            });
            onTokenRefresh(function () {
                messaging.getToken()
                    .then(function (refreshedToken) {
                        console.log('Token refreshed.');
                        tokenElement.innerHTML = "Token is " + refreshedToken;
                    }).catch(function (err) {
                        errorElement.innerHTML = "Error: " + err;
                        console.log('Unable to retrieve refreshed token ', err);
                    });
            });
            console.log("clicked");
        }

    </script>

</head>

<body>
    <main>
        <h1>Welcome to Clouding</h1>
        <div id="token" style="color:lightblue" role="alert"></div>
        <div id="message" style="color:lightblue" role="alert"></div>
        <div id="notification" style="color:green" role="alert"></div>
        <div id="error" style="color:red" role="alert"></div>
        <script>
            messageElement = document.getElementById("message")
            tokenElement = document.getElementById("token")
            notificationElement = document.getElementById("notification")
            errorElement = document.getElementById("error")
        </script>
        <button id="btnPermissions">Enable Firebase Messaging</button>

    </main>

</body>

firebase-消息-sw.js:

// Import and configure the Firebase SDK

// Import the functions you need from the SDKs you need
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js');

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyDOVN1qOGzsD6AI-2jA05LpfQIJ5aoCuD4",
  authDomain: "clouding-aa740.firebaseapp.com",
  projectId: "clouding-aa740",
  storageBucket: "clouding-aa740.appspot.com",
  messagingSenderId: "1059589787087",
  appId: "1:1059589787087:web:cdd636057d2a921ccdd6ba",
  measurementId: "G-CD2BEK39LZ"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const messaging = getMessaging(app);

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// Keep in mind that FCM will still show notification messages automatically 
// and you should use data messages for custom notifications.
// For more info see: 
// https://firebase.google.com/docs/cloud-messaging/concept-options
messaging.onBackgroundMessage(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

新的 Firebase SDK 9 版本中不存在 onTokenRefresh。我也在 API References 中搜索过它或替代品,但找不到。

能否请您取消推荐带有 onTokenRefresh 的部分,看看是否至少有一些错误消失了。

您也不需要自己申请权限。 getToken 会自动完成。

更新:

它在我这边是如何起作用的。从 firebase-messaging-sw.js 中删除所有代码(至少现在)但保留空文件。并放入有效的 Firebase Cofnig 数据(也是有效的 vapidKey):

这是我的一个项目的配置,结果是:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clouding</title>
    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
        import { getMessaging, getToken, onMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries

        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {
           apiKey: 'AIzaSyBQAmNJ2DbRyw8PqdmNWlePYtMP0hUcjpY',
            authDomain: 'react-most-wanted-3b1b2.firebaseapp.com',
            databaseURL: 'https://react-most-wanted-3b1b2.firebaseio.com',
            projectId: 'react-most-wanted-3b1b2',
            storageBucket: 'react-most-wanted-3b1b2.appspot.com',
            messagingSenderId: '258373383650',
            appId: '1:258373383650:web:b49ad5dd28da999a',
        };
        window.addEventListener("click", (e) => {
            switch (e.target.id) {
                case "btnPermissions":
                    initFirebaseMessagingRegistration();
                    break;
            }
        });
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        //        const analytics = getAnalytics(app);
        const messaging = getMessaging(app);

        function initFirebaseMessagingRegistration() {

            // Don't forget your vapidKey here
            getToken(messaging, { vapidKey: "BEthk1-Qmoh9opZbi1AUZpxANTu6djVRDph4MLpyO2Qk6Dglm1Sa8Yt_pYi4EhYi3Tj-xgLqUktlbNuP_RP6gto" })
                .then((t) => {
                    tokenElement.innerHTML = "Token is " + t;
                })
                .catch(function (err) {
                    errorElement.innerHTML = "Error: " + err;
                    console.log("Didn't get notification permission", err);
                });

            onMessage(messaging, (payload) => {
                console.log("Message received. ", JSON.stringify(payload));
                notificationElement.innerHTML =
                    notificationElement.innerHTML + " " + payload.data.notification;
            });
        }

    </script>

</head>

<body>
    <main>
        <h1>Welcome to Clouding</h1>
        <div id="token" style="color:lightblue" role="alert"></div>
        <div id="message" style="color:lightblue" role="alert"></div>
        <div id="notification" style="color:green" role="alert"></div>
        <div id="error" style="color:red" role="alert"></div>
        <script>
            messageElement = document.getElementById("message")
            tokenElement = document.getElementById("token")
            notificationElement = document.getElementById("notification")
            errorElement = document.getElementById("error")
        </script>
        <button id="btnPermissions">Enable Firebase Messaging</button>

    </main>

</body>

</html>

这是令牌: