为什么我无法在 Firebase Vanilla JS 应用中注册 Service Worker?

问题描述 投票:0回答:1

我有这个 javascript 应用程序,它可以简单地初始化并显示 firebase 推送通知:

import { initializeApp } from "firebase/app";
import { getMessaging, onMessage, getToken } from "firebase/messaging";

const firebaseConfig = {
  // config
};
  
  
const vapidKey = //vapid;


console.log("Here");
// Initialize Firebase  
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
    
Notification.requestPermission().then(function(permission) { 
    console.log('permiss', permission)

    if (permission === 'granted') {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker
            .register(new URL('./firebase-messaging-sw.js', import.meta.url), {type: 'module'} )
            .then(function (registration) {
                console.log('Registration successful, scope is:', registration.scope)

                getToken(messaging,{vapidKey})
                    .then(function (currentToken) {
                        if (currentToken) {
                            console.log("Get token:",currentToken)
                            document.getElementById("token").innerText=currentToken

                            onMessage(messaging, (payload) => {
                                console.log(payload)
                            });
                        }
                    }).catch(error => console.error(error));
            })
            .catch(function (err) {
                console.log('Service worker registration failed, error:', err)
            })
        }
    }
});

我还初始化了服务工作者:

import { initializeApp } from 'firebase/app';
import { getMessaging } from "firebase/messaging";
import { onBackgroundMessage } from 'firebase/messaging/sw'

const firebaseConfig = {
 // firebase Config
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

onBackgroundMessage(messaging, (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: 'icon.png'
  };

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

但是我收到错误:

服务工作人员注册失败,错误:TypeError:ServiceWorker脚本位于https://172.161.10.2:1234/firebase-messaging-sw.js?1715685024290范围https://172.161.10.2:1234/引发了脚本评估期间出现异常。

但是我在js上找不到异常,你能帮我吗?

我正在使用一个简单的包裹应用程序来提供服务:

npx parcel --https --host 0.0.0.0 --cert=/home/node/ssl/www.crt --key=/home/node/ssl/www.key src/index.html

我的 html 是:

<!DOCTYPE html>
<html>
    <head>
        <title>Using Push.js to Display Web Browser Notifications</title>
        <link rel="stylesheet" href="./styles.css">
    </head>
    <body>
        <h1>Display Web Browser Notifications</h1>
        <pre><code id="token"></code></pre>
        <script type="module" src="./index.js" />
    </body>
</html>

我加载了 npm 安装的 firebase:

{
  "name": "firebasedemo",
  "version": "1.0.0",
  "description": "",
  "browserslist": [
    "since 2017-06"
  ],  
  "scripts": {
    "start": "parcel src/index.html",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "UNLICENCED",
  "devDependencies": {
    "parcel": "^2.12.0",
    "process": "^0.11.10"
  },
  "dependencies": {
    "firebase": "^10.12.0"
  }
}

javascript firebase firebase-cloud-messaging service-worker
1个回答
0
投票

在您的 Service Worker

firebase-messaging-sw.js
处,您需要使用从
getMessaging
加载
firebase/messaging/sw
而不是
firebase/messaging

因此

firebase-messaging-sw.js
应该是:

import { initializeApp } from 'firebase/app';
import { onBackgroundMessage,getMessaging } from 'firebase/messaging/sw'

// rest of code

index.js
(加载工作线程的位置
firebase-messaging-sw.js
)应该以:

开头
import { initializeApp } from "firebase/app";
import { getMessaging, onMessage, getToken, isSupported } from "firebase/messaging";
© www.soinside.com 2019 - 2024. All rights reserved.