flutterfire
flutterfire copied to clipboard
🐛 [firebase_messaging] Error when setting up Firebase Messaging for web: `The script has an unsupported MIME type ('text/html').`
Bug report
Describe the bug
When I start my web application, I'm unable to use Firebase Messaging for the web.
[firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:51068/firebase-cloud-messaging-push-scope') with script ('http://localhost:51068/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). .
Steps to reproduce
Steps to reproduce the behavior:
- Run
flutter create bug - Run
cd bug - Run
flutterfire configure - Choose Firebase project
- Add
firebase_coreas a dependency - Add
firebase_messagingas a dependency - Follow the Firebase Messaging Docs for Flutter a. Generate Application Identity key in Firebase Console: Project settings -> Cloud messaging
Expected behavior
Firebase Messaging should work.
Additional context
#9215 is not helpful because there is Firebase initialized via index.html. I need to initialize via Dart.
Flutter doctor
Run flutter doctor and paste the output below:
Click To Expand
Nils-MBP-13-M1-4:app nils$ flutter --version
Flutter 3.7.10 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 4b12645012 (4 weeks ago) • 2023-04-03 17:46:48 -0700
Engine • revision ec975089ac
Tools • Dart 2.19.6 • DevTools 2.20.1
I can reproduce the issue using the steps outlined above and the code sample from the example app. With the example app, I get the error after accepting the permission to allow notifications.
Error: [firebase_messaging/failed-service-worker-registration] Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:55880/firebase-cloud-messaging-push-scope') with script ('http://localhost:55880/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). .
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 299:10 createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 355:28 _throw
dart-sdk/lib/core/errors.dart 120:5 throwWithStackTrace
dart-sdk/lib/async/zone.dart 1385:11 callback
dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 <fn>
I get the same this is mi firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/9.22.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.22.1/firebase-messaging.js");
firebase.initializeApp({
apiKey: "...",
authDomain: "....
projectId: ".....",
storageBucket: ".....",
messagingSenderId: "....",
appId: "...",
measurementId: "..."
});
const messaging = firebase.messaging();
and this is my index.html
<script>
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// ADD THIS LINE
navigator.serviceWorker.register('/firebase-messaging-sw.js');
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
// ...
});
}
</script>
I tried like in 2345 ways, always getting this error after trying to retrieve token
Error: FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope
('http://localhost:5519/firebase-cloud-messaging-push-scope') with script ('http://localhost:5519/firebase-messaging-sw.js'): ServiceWorker script
evaluation failed (messaging/failed-service-worker-registration).
Hi @nilsreichardt,
I've come across similar issues when setting up Firebase Messaging for the web. To address this problem, I've made modifications to the official firebase_messaging plugin for the web. You might find my version helpful in resolving the MIME type error you're facing.
To use this version of the plugin, simply add the following dependency_overrides to your pubspec.yaml:
dependency_overrides:
firebase_messaging_web:
git:
url: https://github.com/Bikram40/firebase_messageing_web.git
Make sure to run flutter pub get after adding the override to fetch the plugin. This should prioritize my version of firebase_messaging_web in your project and hopefully address the error you've mentioned.
I'm experiencing the same issue. After trolling through StackOverflow etc. for hours, I've found some partial solutions that seem to just kick the can down the road (the same/similar service worker error shows up later). Further, several sources say you have to create a custom firebase-messaging-sw.js file, but there is no indication that this is necessary in the documentation (at least from what I've seen).
I'm experiencing the same error after upgrading to flutter 3.16.2.
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.16.2, on macOS 13.6.1 22G313 darwin-arm64, locale en-KR)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] IntelliJ IDEA Ultimate Edition (version 2023.2.5)
[✓] VS Code (version 1.71.1)
[✓] VS Code (version 1.75.1)
[✓] Connected device (3 available)
[✓] Network resources
• No issues found!
Same here ... Any fix ?
Same here ... Any fix ?
- Add 'firebase-messaging-sw.js' to the web folder.
importScripts("https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js");
firebase.initializeApp({
apiKey: '........',
appId: '.......',
messagingSenderId: '..........',
projectId: '........',
authDomain: '...........',
storageBucket: '...........',
measurementId: '............',
});
// Necessary to receive background messages:
const messaging = firebase.messaging();
// Optional:
messaging.onBackgroundMessage((m) => {
console.log("onBackgroundMessage", m);
});
If you are using a real-time database, add databaseUrl.
databaseURL: 'https://..........................firebasedatabase.app',
- index.html
Unfortunately, Flutter does not automatically support server work. In my case this solved the problem.
Same here ... Any fix ?
Sorry, I tested a bit more. It's still unstable. The server work is registered, but it throws additional errors like this. Also, reloading again allowed me to get the token without errors.
AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
Update: index.html
<script>
// The value below is injected by flutter build, do not touch.
const serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
<!-- <script src="/firebase-messaging-sw.js"></script> -->
</head>
<body>
<script src="main.dart.js" type="application/javascript"></script>
<script>
if ( 'serviceWorker' in navigator) {
window.addEventListener('load', function (ev) {
// Fcm init
navigator.serviceWorker.register('/firebase-messaging-sw.js').then(function(registration) {
console.log('>>> Service Worker registration successful!');
}).catch(function(error) {
console.error('>>> Service Worker registration failed:', error);
});
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function (engineInitializer) {
engineInitializer.initializeEngine().then(function (appRunner) {
appRunner.runApp();
});
}
});
});
}
</script>
</body>
</html>
Same problem here.
Error Log:
Performing hot restart...
Waiting for connection from debug service on Edge...
Restarted application in 265ms.
Permission granted: AuthorizationStatus.authorized
Error: Assertion failed: file:///C:/Users/<Username>/AppData/Local/Pub/Cache/hosted/pub.dev/firebase_crashlytics_platform_interface-3.6.16/lib/src/platform_interface/platform_interface_crashlytics.dart:31:12
pluginConstants['isCrashlyticsCollectionEnabled'] != null
is not true
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:3 throw_
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 35:3 assertFailed
packages/firebase_crashlytics_platform_interface/src/platform_interface/platform_interface_crashlytics.dart 31:28 instanceFor
packages/firebase_crashlytics/src/firebase_crashlytics.dart 24:69 get [_delegate]
packages/firebase_crashlytics/src/firebase_crashlytics.dart 192:22 setCrashlyticsCollectionEnabled
packages/mindstreamers_app/main.dart 71:6 main
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50 <fn>
dart-sdk/lib/async/zone.dart 1661:54 runUnary
dart-sdk/lib/async/future_impl.dart 162:18 handleValue
dart-sdk/lib/async/future_impl.dart 846:44 handleValueCallback
dart-sdk/lib/async/future_impl.dart 875:13 _propagateToListeners
dart-sdk/lib/async/future_impl.dart 647:5 [_completeWithValue]
dart-sdk/lib/async/future_impl.dart 721:7 callback
dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7 <fn>
Error: FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:49592/firebase-cloud-messaging-push-scope') with script ('http://localhost:49592/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). (messaging/failed-service-worker-registration).
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 327:10 createErrorWithStack
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 337:28 _throw
dart-sdk/lib/core/errors.dart 120:5 throwWithStackTrace
dart-sdk/lib/async/zone.dart 1386:11 callback
dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7
The errors disappears with the execution of the command flutter pub add firebase_messaging, which updates the dependencies, but the app still hangs up at this point.
The same. After update to Flutter 3.16 FCM on web stopped working. I have the following error:
Uncaught (in promise) Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
Notifications worked just before the update and still working on the production version of the app which is not updated.
If I reload the page several times, reset permission and ask for it again, I won't have this error, but notifications still will not work.
The initial bug report by @nilsreichardt no longer appears. In terms of the other noted exception AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker, this has also been resolved by having another attempt in this try/catch here. I'd also recommend updating to the latest firebase messaging web implementation here as per Flutter 3.21, see here