firebase-js-sdk
firebase-js-sdk copied to clipboard
Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
Operating System
MacOS
Browser Version
All browser
Firebase SDK Version
10.2.0
Firebase SDK Product:
Messaging
Describe your project's tooling
Nextjs 13 with Page setup. Example Repo -> https://github.com/2manoj1/nextjs-firebase-example/tree/main
Describe the problem
Same problem as https://github.com/firebase/firebase-js-sdk/issues/5797 Sometimes calling messaging getToken returns the error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. It seems to occur on the first page load and clear storage with unregister sw, when the user refreshes the notifications work and there's no error anymore.
Steps and code to reproduce issue
- Open https://nextjs-firebase-example.vercel.app/
- Open inspect element - F12
- Clear Storage with Service Worker
- Refresh the browser.
- See the error. Its coming also first time
After remove useCallback and made some changes check its working. https://github.com/2manoj1/nextjs-firebase-example/commit/0f193f5473ea38864816a4925a280aa8f54dddcf
Why this occurred now. any config changes require? How fix this issue?
Hi @2manoj1, thanks for reporting this issue. I was able to reproduce the behavior you mentioned. Let me check what we can do for this issue or bring someone here that can provide more context about it. I’ll update this thread if I have any information to share.
This issue still coming in first time. Also clear cache way. My workaround not working. Look like service worker firebase having issues.
@jbalidiong any solutions? Any workaround how to fix this issue. In Production also coming this issue.
@2manoj1, apologies for the delay. I have discussed this with our FCM team and this is working as intended. The 404 that you've received from this screenshot is due to the indexDB being cleared and then there will be no token(s) to be deleted. With your app, I experience the same behavior. However, after receiving the warning, a new token will be created. Is this not the same as yours? Are you receiving any other errors aside from the previous one or you are not able to receive a new token?
@jbalidiong This issue still persist. On new device try to getToken first time. Its error coming and token is null.
Also I tried clear storage and unregister service worker or clear everything. Its reproducible. Without 2 refresh this cause issue.
Look like before ready service worker calling. await swRegistration.serviceWorker.ready
missing before call subscribe.
I am unfamiliar w/ next but your repo doesn't seem to have a required firebase-messaging-sw.js file https://github.com/search?q=repo%3A2manoj1%2Fnextjs-firebase-example%20firebase-messaging-sw.js&type=code.
Per public doc https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token: "FCM requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client setup process".
(Also btw, you are leaking your api key in the repo shared. Maybe you'd like to obfuscate or hide it. )
@zwu52 sw file already in public folder please check. public/firebase-messaging-sw.js
API key not required to hide. Watch official firebase video. If I hide also SPA app expose in source. Don't worry about key.
- FYI it's working only first time having issue. Which I raise here
My hypothesis is some intricacies on how next loads scripts cause the incompatibilities between the SDK & the code.
I suspect it's not a race issue you suspected "Look like before ready service worker calling. await swRegistration.serviceWorker.ready missing before call subscribe." given the registration call is a blocking call here https://github.com/firebase/firebase-js-sdk/blob/master/packages/messaging/src/helpers/registerDefaultSw.ts#L27.
Another pointer to the loading of the sw path here https://github.com/firebase/firebase-js-sdk/blob/master/packages/messaging/src/helpers/registerDefaultSw.ts#L28. The SDK is expecting the sw script to live in a root directory.
Can you try to play around the SDK & figure out how to make it compatible?
I am trying but not able to figure out how use my fork version.
@jbalidiong are get chance to see this https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1693877829 ?
I have the same problem, but with the flutter package:
When I run the app for the first time that's when I get that error, but if I reload the permissions my app works fine, this is where the app fails:
I am following the process correctly, first I made the permissions request and then I got the token.
And well, this is a new error of my application, this application was working correctly, I did not change anything and now I have this error.
Workaround - if fail call again get token. 3 Retry I did and that's way solve the fix
Same issue here https://github.com/firebase/firebase-js-sdk/issues/7693
i have the same issue.
I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears.
is there any solution for that?
I noticed this happened when I used Chrome, I switched to Firefox and I didn't have it anymore with exactly the same code.
But after some code changes I made it work again in chrome, not even sure why exactly or how it got fixed.
Same issue here, I get this error every time I clear the website data and reset the permissions.
Error sending user token DOMException: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
same issue here. It thrown error always the first time, after reload works fine. I'm using Opera
Same issue here with Flutter 3.16
Permission → User Action → Token
This setup seems to avoid the no active Service Worker
error for a Flutter based Firebase Messaging web app in my limited testing:
-
requestPermission()
must now be called separately & beforegetToken()
, - there needs to be some user interaction with the app prior to
getToken()
- after 1) & 2) we can safely request a token and avoid the
no active Service Worker
error.
Previously just a getToken()
call would automatically request push notification permission if it hadn't already been done and then the token would be retrieved directly after without error.
Even the example app on Github by the Firebase team has the same no active Service Worker
error:
https://github.com/firebase/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example
(The example app tries to getToken()
on startup without user interaction. See the below run output.)
[xxxx:~/docker/flutterfire/packages/firebase_messaging/firebase_messaging/example]
$ flutter run -d chrome
Launching lib/main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome... 28.8s
This app is linked to the debug service: ws://127.0.0.1:49500/L0CHcF9eCjo=/ws
Debug service listening on ws://127.0.0.1:49500/L0CHcF9eCjo=/ws
🔥 To hot restart changes while running, press "r" or "R".
For a more detailed help message, press "h". To quit, press "q".
A Dart VM Service on Chrome is available at: http://127.0.0.1:49500/L0CHcF9eCjo=
The Flutter DevTools debugger and profiler on Chrome is available at: http://127.0.0.1:9101?uri=http://127.0.0.1:49500/L0CHcF9eCjo=
Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
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 <fn>
Application finished.
Has there been some JavaScript added to FlutterWeb/FirebaseCore/FirebaseMessaging that prevents the service worker from being "fully ready" until there has been some user interaction with the web app?
(I use quotes on "fully ready" as the ServiceWorker is marked as ready if you check the JS console, but will still throw the error if you haven't interacted with the app before making the getToken()
call. To check I added a navigator.serviceWorker.ready.then(reg => console.log("Service Worker Ready"));
line to index.html after the const app = initializeApp(firebaseConfig);
line.
As a test (using Flutter's Demo / "You have pushed the button this many times:" app on a new project), we can request push notification permission in main(), then call getToken() on a FloatingActionButton (FAB) onPressed handler and this will work consistently without any errors on first getToken()
request:
/// Request push notification permissions at app start
void main() async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseMessaging.instance.requestPermission();
runApp(const MyApp());
}
Then in _MyHomePageState, get the token in _incrementCounter()
which is the onPressed handler for the FAB:
void _incrementCounter() {
getFCMToken(); // see definition below
setState(() {
_counter++;
});
}
The getFCMToken()
method above is:
Future<String?> getFCMToken() async {
print('Getting Fcm Token...');
fcmToken = await FirebaseMessaging.instance.getToken(vapidKey: "YourVAPIDKeyHeRe");
print('fcmToken: $fcmToken');
return fcmToken;
}
This works fine, even on first run, without the no active Service Worker
error.
The bizarre thing: if you call getToken()
without user interaction, you'll likely get the no active Service Worker
error. (The error isn't 100%, but pretty often, like 80%.)
For example, try to call getToken()
in initState()
of _MyHomePageState
, after the page is built:
@override
void initState() {
super.initState();
listenNotifications(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
print('postFrameCallback, calling getFCMToken');
getFCMToken().then((tkn) => print('tkn: $tkn'));
});
}
This will likely throw the no active Service Worker
error.
Adding in a delay will likely still get you the error:
@override
void initState() {
super.initState();
listenNotifications(context);
Future.delayed(const Duration(seconds: 10)).then((_) => getFCMToken());
}
Any ideas on what's going on? I'm not familiar enough with the JS side of Flutter / Firebase to debug this deeper.
I'm using:
firebase_core: ^2.24.2
firebase_messaging: ^14.7.10
This is my Flutter doctor output:
$ flutter doctor -v
[✓] Flutter (Channel stable, 3.16.5, on macOS 14.2.1 23C71 darwin-x64, locale en-US)
• Flutter version 3.16.5 on channel stable at /Users/xxxx/fvm/versions/stable
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 78666c8dc5 (4 weeks ago), 2023-12-19 16:14:14 -0800
• Engine revision 3f3e560236
• Dart version 3.2.3
• DevTools version 2.28.4
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
• Android SDK at /Users/xxxx/Library/Android/sdk
• Platform android-33, build-tools 33.0.0
• ANDROID_SDK_ROOT = /Users/xxxx/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 15.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 15C65
• CocoaPods version 1.11.3
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 2022.2)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
[✓] VS Code (version 1.85.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.80.0
[✓] Connected device (2 available)
• macOS (desktop) • macos • darwin-x64 • macOS 14.2.1 23C71 darwin-x64
• Chrome (web) • chrome • web-javascript • Google Chrome 120.0.6099.234
[✓] Network resources
• All expected network resources are available.
• No issues found!
mesmo erro....
alguma solução além do que foi dito pelo @ben-xx ?
i have the same issue.
I get this error: "Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker " when I run my Flutter app for the first time on Chrome browser, but if I restart the app or refresh the browser page, the error disappears.
is there any solution for that?
me too, but when try a test, the message on background works
I'm facing the same issue
same issue for me on flutter web latest firebase:
Uncaught (in promise) Error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
everything work after page reload, so its just the first time
Hi guys,
Can you help me resolve this?
👆 Looks like a firebase js SDK issue, when I have the following service worker file.
/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js');
const firebaseConfig = {
apiKey: "REDACTED_AS_ASKED_BY_OWNER",
authDomain: "REDACTED_AS_ASKED_BY_OWNERi",
projectId: "crafty-biplane-405403",
storageBucket: "REDACTED_AS_ASKED_BY_OWNER",
messagingSenderId: "REDACTED_AS_ASKED_BY_OWNER",
appId: "REDACTED_AS_ASKED_BY_OWNER",
measurementId: "REDACTED_AS_ASKED_BY_OWNER"
};
// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
// eslint-disable-next-line no-undef
const messaging = firebase.messaging();
messaging.onBackgroundMessage(payload => {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
// self.registration.showNotification(notificationTitle, notificationOptions);
});
Hi guys,
Can you help me resolve this?
👆 Looks like a firebase js SDK issue, when I have the following service worker file.
/* eslint-disable no-undef */ importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js'); const firebaseConfig = { apiKey: "REDACTED_AS_ASKED_BY_OWNER", authDomain: "REDACTED_AS_ASKED_BY_OWNERi", projectId: "crafty-biplane-405403", storageBucket: "REDACTED_AS_ASKED_BY_OWNER", messagingSenderId: "REDACTED_AS_ASKED_BY_OWNER", appId: "REDACTED_AS_ASKED_BY_OWNER", measurementId: "REDACTED_AS_ASKED_BY_OWNER" }; // eslint-disable-next-line no-undef firebase.initializeApp(firebaseConfig); // Retrieve firebase messaging // eslint-disable-next-line no-undef const messaging = firebase.messaging(); messaging.onBackgroundMessage(payload => { console.log('Received background message ', payload); const notificationTitle = payload.notification.title; const notificationOptions = { body: payload.notification.body, }; // self.registration.showNotification(notificationTitle, notificationOptions); });
🛑 Not the perfect solution
So I could not solve this, but temporarily I show try...catch
the error & check the error message
. If it has this or something similar, I proceed to get the FCM Token generated again from firebase (may be in 1000ms).
@arc-prvh check this comment https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1711705543
https://github.com/2manoj1/nextjs-firebase-example/blob/2b76b7d5e6ce58124c15a9cb4e071645b00f5c49/src/config/useFcm.tsx#L61
When fail retry call again - I did 3 times retry logic. Its working, I am using in prod. No solution from FCM team yet
No solution for this issue?
So one way of doing this is waiting for the browser notification. Once received, just refresh the browser from javascript. Tell the user "configuring things in the background". That said, also pay attention to the UX part of the app. If you are doing something business critical do not just refresh anything. Wait for the user the next time they come. Best Regards,
Anweshan Roy Chowdhury, @.***) Full Stack Developer - Level 1, Pravaah Consulting Inc.
On Fri, Mar 29, 2024 at 4:59 PM Dat Vu @.***> wrote:
No solution for this issue?
— Reply to this email directly, view it on GitHub https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-2027108740, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5NFSBHK7ZWBGOKPOSZW3HLY2VGDDAVCNFSM6AAAAAA3X74SSWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMRXGEYDQNZUGA . You are receiving this because you were mentioned.Message ID: @.***>