![](/img/trans.png)
[英]Removing FCM from web app -> FirebaseError: Messaging: We are unable to register the default service worker
[英]FirebaseError : We are unable to register the default service worker
我正在使用 FCM web 应用程序通知向浏览器发送通知。我的代码如下。
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);
});
它工作正常并在 chrome 的本地主机服务器上生成令牌,但在我的托管服务器上不起作用。
我的托管服务器出现以下错误。
发生错误。FirebaseError:消息:我们无法注册默认服务工作者。 操作不安全。 (消息传递/服务工作者注册失败)。
如果有人对此有任何想法,请指导我。
在您的根文件夹中创建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);
});
}
这是因为 Service Worker 在 https 或 localhost 上工作。 因此,如果您的网站没有 SSL 证书,Service Worker 将无法工作。
2021 使用 create-react-app 的工作流程
在 /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); });
现在在 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*/
很可能 HTTPd 没有正确地为带有内容类型application/javascript
标头的 JS 文件提供服务。 如果没有任何实时 URL,则无法验证这种怀疑 - 而在这种情况下,可以为服务器配置 MIME 类型 - 或者作为快速修复:使用 PHP 设置丢失的内容类型 HTTP 标头。
尝试在您firebase-messaging-sw.js
添加以下示例, firebase-messaging-sw.js
firebase-messaging-sw.js
放在您的 react 应用程序的公共文件夹中。
// 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);
});
我使用 Amazon CloudFront 来托管我的生产环境。 当它在本地主机上工作时,我在生产(https)上收到了这个错误。 在查看 Amazon S3 存储桶(针对 CloudFront)后,我注意到在生产部署期间没有生成 Service Worker 文件。 只需修改部署脚本即可解决问题。
所以确保生成了 service worker 文件(Chrome DevTools -> Sources -> Filesystem)。
您需要确保“firebase-messaging-sw.js”已存在于您的公共文件夹中
我也遇到了这个错误,因为我的firebase.initializeApp({})
缺少appId
,您的配置中也缺少它。
尽管此错误有多个线程和已解决的问题,但如果此错误直接从控制台复制到搜索,则此线程会出现在 google 结果的顶部,因此在这里分享我的经验是有意义的。
正如其他答案所暗示的那样:
firebase-messaging-sw.js
在主机根目录中公开可用即使在检查了所有这些之后,我也遇到了同样的错误。
所以最后求助于谷歌文档,这次我在这里仔细阅读
从 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');
其中<v9+>
是 9 以上的 Firebase SDK 版本
大功告成!!
我正在使用 firebase 版本 9.9.1 解决这个问题的步骤:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.