![](/img/trans.png)
[英]FirebaseError browserErrorMessage: "Failed to register a ServiceWorker: ServiceWorker script evaluation failed"
[英]FCM getToken() Failed to register a ServiceWorker for scope error Flutter web
在我的應用程序中,對於網絡版本,我使用包firebase 7.3.0
。 我首先使用單例實例化 Firebase 應用程序,然后實例化 Messaging(),就像我在我的應用程序中使用的所有其他 Firebase 服務所做的那樣:
App firebase = FirebaseWeb.instance.app;
var firebaseMessaging = messaging();
我有subscribeToTopic()
方法,它首先調用getMessagingToken()
方法,因為它需要返回的令牌,但getMessagingToken()
拋出錯誤:
PlatformPushNotificationWeb.getMessagingToken() getToken error: FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:5000/firebase-cloud-messaging-push-scope') with script ('http://localhost:5000/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration). (messaging/failed-service-worker-registration)
Future<String> getMessagingToken() async {
String token;
await firebaseMessaging.requestPermission().timeout(Duration(seconds: 5)).then((value) {
print('PlatformPushNotificationWeb.getMessagingToken() requestPermission result is $value');
}).catchError((e) => print('PlatformPushNotificationWeb.getMessagingToken() requestPermission error: $e'));
await firebaseMessaging.getToken().then((value) {
print(' PlatformPushNotificationWeb.getMessagingToken() token is $value');
token = value;
}).catchError((e) => print('PlatformPushNotificationWeb.getMessagingToken() getToken error: $e'));
return token;
}
我檢查並在我的index.html
中存在 firebase-messaging:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>fixit cloud biking</title>
<!-- <meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">-->
<meta name="google-signin-client_id" content="xxxxxxxxxx.apps.googleusercontent.com">
<!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
</head>
<!--<body>-->
<body id="app-container">
<script src="main.dart.js?version=45" type="application/javascript"></script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-remote-config.js"></script>
</body>
</html>
現在,錯誤顯示'http://localhost:5000/firebase-messaging-sw.js'
不是 firebase firebase-messaging.js
作為 index.html file. I noticed that
file. I noticed that
Messaging() is not directly available through firebase app instance as it would be for other services, for Storage would be
firebase.storage()`。 我是否缺少為消息傳遞設置其他內容?
找到這篇文章https://medium.com/@rody.davis.jr/how-to-send-push-notifications-on-flutter-web-fcm-b3e64f1e2b76並發現 Firebase Cloud 確實有更多設置在網絡上發送消息。
在index.html
有一個要添加的腳本:
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
// navigator.serviceWorker.register("/flutter_service_worker.js");
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
在項目web
文件夾中創建一個新文件firebase-messaging-sw.js
,您firebase-messaging-sw.js
在其中導入firebase-messaging-sw.js
包(匹配index.html
版本)、初始化 Firebase app 並設置 BackgroundMessageHandler。 如果我使用單例初始化 Firebase 應用程序,則實例化 messages messaging()
會引發語法錯誤,因此需要使用所有參數對其進行初始化,否則后台消息將不起作用。
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.15.5/firebase-messaging.js");
//Using singleton breaks instantiating messaging()
// App firebase = FirebaseWeb.instance.app;
firebase.initializeApp({
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://project-id.firebaseio.com',
projectId: 'project-id',
storageBucket: 'project-id.appspot.com',
messagingSenderId: 'sender-id',
appId: 'app-id',
measurementId: 'G-measurement-id',
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("New Message");
});
return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
console.log('notification received: ', event)
});
所以現在, getToken()
和subscribeToTopic()
以及onMessage()
按預期工作。
在我的集團中,我在onMessage()
上有一個偵聽器,它(在網絡上)Stream 我轉換為Stream<Map<String,Dynamic>>
作為firebase_messaging
(在設備上)從以下位置返回:
Stream<Map<String, dynamic>> onMessage() async* {
print('PlatformPushNotificationWeb.onMessage() started');
handleData(Payload payload, EventSink<Map<String, dynamic>> sink) {
Map<String,dynamic> message = {
'notification': {
'title': payload.notification.title,
'body': payload.notification.body,
'sound': true
},
'data': payload.data
};
sink.add(message);
}
final transformer = StreamTransformer<Payload, Map<String, dynamic>>.fromHandlers(
handleData: handleData);
yield* firebaseMessaging.onMessage.transform(transformer);
}
希望它可以幫助其他人。 干杯。
事實證明,您只需在您的 web 項目文件夾中創建一個名為firebase-messaging-sw.js
文件,並在其中注釋掉一些 JavaScript,然后 Flutter 就會停止抱怨。
還用這個修改 index.html:
<script>
if ('serviceWorker' in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("firebase-messaging-sw.js");
});
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
我真的不知道為什么會這樣,但這比放置一些無用的 JavaScript 代碼要好。
自 2022 年 12 月起,只需在 Flutter 應用程序的web
目錄根目錄下創建一個空firebase-messaging-sw.js
文件即可解決此問題。
在此之前,您當然要按照以下步驟將 Firebase 添加到您的應用程序: https ://firebase.google.com/docs/flutter/setup
dart pub global activate flutterfire_cli
flutterfire configure
然后
在您的 lib/main.dart 文件中,導入 Firebase 核心插件和您之前生成的配置文件:
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
最后
同樣在您的 lib/main.dart 文件中,使用配置文件導出的 DefaultFirebaseOptions 對象初始化 Firebase:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.