FirebaseError :我们无法注册默认服务工作者

Sac*_*nki 6 firebase firebase-cloud-messaging

我正在使用 FCM Web 应用程序通知向浏览器发送通知。我的代码如下。

<script>
var config = {
    apiKey: "<API-KEY>",
    authDomain: "<AUTH-DOMAIN>.firebaseapp.com",
    databaseURL: "<DATABASE>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDERID>",
  };
  firebase.initializeApp(config);

const messaging = firebase.messaging();
    messaging.requestPermission()
            .then(function(){
                console.log("GRANTED");
                console.log(messaging.getToken());
                return messaging.getToken();
            })
            .then(function(token){
                console.log(token);
            })
            .catch(function(err){
                console.log('Error Occurred.' + err)
            });

messaging.setBackgroundMessageHandler(function(payload){
  const title = "Hello World";
  const option = { body: payload.data.status }
  return self.registration.showNotification(title,option);
});

</script>
Run Code Online (Sandbox Code Playgroud)

它工作正常并在 chrome 的 localhost 服务器上生成令牌,但在我的托管服务器上不起作用。

我的托管服务器出现以下错误。

Error Occurred.FirebaseError: Messaging: 我们无法注册默认的 Service Worker。操作不安全。(消息/失败的服务工作者注册)。

如果有人对此有任何想法,请指导我。

小智 23

2021 年 create-react-app 工作流程

  1. 在 /public 文件夹中使用以下代码创建文件 firebase-messaging-sw.js :

     // Scripts for firebase and firebase messaging
     importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
     importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js");
    
     // Initialize the Firebase app in the service worker by passing the generated config
     const firebaseConfig = {
       apiKey: "YOURDATA",
       authDomain: "YOURDATA",
       projectId: "YOURDATA",
       storageBucket: "YOURDATA",
       messagingSenderId: "YOURDATA",
       appId: "YOURDATA",
       measurementId: "YOURDATA",
     };
    
     firebase.initializeApp(firebaseConfig);
    
     // Retrieve firebase messaging
     const messaging = firebase.messaging();
    
     messaging.onBackgroundMessage(function(payload) {
       console.log("Received background message ", payload);
    
       const notificationTitle = payload.notification.title;
       const notificationOptions = {
         body: payload.notification.body,
       };
    
       self.registration.showNotification(notificationTitle, notificationOptions);
     });
    
    Run Code Online (Sandbox Code Playgroud)
  2. 现在在 app.js 或任何您需要的地方添加此代码。

    /*firebase daniel start*/
    import { initializeApp } from "firebase/app";
    import { getMessaging, getToken, onMessage } from "firebase/messaging";
    
    const firebaseConfig = {
      apiKey: "YOURDATA",
      authDomain: "YOURDATA",
      projectId: "YOURDATA",
      storageBucket: "YOURDATA",
      messagingSenderId: "YOURDATA",
      appId: "YOURDATA",
      measurementId: "YOURDATA",
    };
    const fapp = initializeApp(firebaseConfig);
    const messaging = getMessaging(fapp);
    
    getToken(messaging, {
      vapidKey:
        "YOURKEY",
    })
      .then((currentToken) => {
        if (currentToken) {
          console.log("Firebase Token", currentToken);
        } else {
          // Show permission request UI
          console.log(
            "No registration token available. Request permission to generate one."
          );
          // ...
        }
      })
      .catch((err) => {
        console.log("An error occurred while retrieving token. ", err);
        // ...
      });
    
    onMessage(messaging, (payload) => {
      console.log("Message received. ", payload);
      // ...
    });
    
    /*firebase daniel end*/
    
    Run Code Online (Sandbox Code Playgroud)


小智 17

在您的根文件夹中创建firebase-messaging-sw.js并将代码粘贴到其中。

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function(err) {
    console.log('Service worker registration failed, error:', err);
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 没有帮助我。仍然收到“消息:我们无法注册默认服务工作者。该操作不安全。” 从我的本地主机启动应用程序。 (3认同)

Anu*_*aji 11

尽管此错误有多个线程和已关闭的问题,但如果将此错误直接从控制台复制到搜索,则此线程会出现在谷歌结果的顶部,因此在这里分享我的经验是有意义的。

正如其他答案所暗示的:

  1. 确保firebase-messaging-sw.js在主机根目录下公开可用
  2. 确保 firebase 配置数据正确并经过双重检查

即使检查了所有这些之后,我也遇到了同样的错误。

所以最后求助于谷歌文档,这次我在这里仔细阅读

从 Firebase v9 开始,他们转向了此提交中提到的compat

所以,里面的导入脚本firebase-messaging-sw.js现在是:

importScripts('https://www.gstatic.com/firebasejs/<v9+>/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/<v9+>/firebase-messaging-compat.js');
Run Code Online (Sandbox Code Playgroud)

<v9+>9 以上的 Firebase SDK 版本在哪里

就这样完成了!!

  • 我的情况一模一样。我信任“一段时间”前编写的非常旧的代码,我只是通过将 importScripts 中的版本号更改为 9.22.X 来更新它。脚本开始引发异常,但消息“我们无法注册”没有显示有关该异常的详细信息。我确信代码是正确的,因为它之前可以工作。解决方案是在“.js”扩展名之前添加“-compat”。 (2认同)

Put*_*M S 9

尝试将以下示例添加到您的firebase-messaging-sw.js反应firebase-messaging-sw.js应用程序中的公共文件夹中。

// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing the generated config
var firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
  console.log('Received background message ', payload);

  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*ler 2

HTTPd 很可能无法正确提供带有内容类型application/javascript标头的 JS 文件。如果没有任何实时 URL,则无法验证这一怀疑 - 但在这种情况下,可以为服务器配置 MIME 类型 - 或者作为快速修复:使用 PHP 设置缺少的内容类型 HTTP 标头。