firebase / firebase-js-sdk

Firebase Javascript SDK
https://firebase.google.com/docs/web/setup
Other
4.76k stars 874 forks source link

Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker #7575

Open 2manoj1 opened 10 months ago

2manoj1 commented 10 months ago

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.

Screenshot 2023-08-21 at 1 45 33 PM

Steps and code to reproduce issue

2manoj1 commented 10 months ago

After remove useCallback and made some changes check its working. https://github.com/2manoj1/nextjs-firebase-example/commit/0f193f5473ea38864816a4925a280aa8f54dddcf

2manoj1 commented 10 months ago
Screenshot 2023-08-21 at 2 23 42 PM

Why this occurred now. any config changes require? How fix this issue?

jbalidiong commented 10 months ago

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.

2manoj1 commented 10 months ago

This issue still coming in first time. Also clear cache way. My workaround not working. Look like service worker firebase having issues.

2manoj1 commented 10 months ago

@jbalidiong any solutions? Any workaround how to fix this issue. In Production also coming this issue.

jbalidiong commented 10 months ago

@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?

2manoj1 commented 10 months ago

@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.

261962363-d01424c8-c42a-4786-8e63-515bcb1949aa
zwu52 commented 10 months ago

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. )

2manoj1 commented 10 months ago

@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.

zwu52 commented 10 months ago

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?

2manoj1 commented 10 months ago

I am trying but not able to figure out how use my fork version.

2manoj1 commented 10 months ago

@jbalidiong are get chance to see this https://github.com/firebase/firebase-js-sdk/issues/7575#issuecomment-1693877829 ?

kessler428 commented 9 months ago

I have the same problem, but with the flutter package:

Screenshot_2023-09-06_at_10 08 01_PM

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:

Screenshot 2023-09-06 at 10 18 07 PM

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.

2manoj1 commented 9 months ago

Workaround - if fail call again get token. 3 Retry I did and that's way solve the fix

dpeese commented 8 months ago

Same issue here https://github.com/firebase/firebase-js-sdk/issues/7693

FarzaneGhb commented 7 months ago

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?

mohamedamara1 commented 6 months ago

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.

OHoussein commented 6 months ago

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

leoalassia commented 5 months ago

same issue here. It thrown error always the first time, after reload works fine. I'm using Opera

LostInDarkMath commented 5 months ago

Same issue here with Flutter 3.16

ben-xx commented 5 months ago

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:

  1. requestPermission() must now be called separately & before getToken(),
  2. there needs to be some user interaction with the app prior to getToken()
  3. 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!
gagjunior commented 5 months ago

mesmo erro.... 2024-01-29_21h51_23 alguma solução além do que foi dito pelo @ben-xx ?

MartinDapper commented 4 months ago

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

ps011 commented 4 months ago

I'm facing the same issue

ascorbic-acid commented 4 months ago

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

arc-prvh commented 4 months ago

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);
});
arc-prvh commented 4 months ago

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).

2manoj1 commented 4 months ago

@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

dab246 commented 3 months ago

No solution for this issue?

arc-prvh commented 3 months ago

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: @.***>

ascorbic-acid commented 3 months ago

any solution for this problem? the workarounds are not reliable

(working on flutter web)

Joseph-Nathan commented 2 months ago

any news ?

Widziks92 commented 2 months ago

Have you got firebase-messaging-sw.js file in public directory? According to https://stackoverflow.com/a/71339854

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.

I know that main problem was different, but solution worked for me. After create empty firebase-messaging-sw.js file in public problem with service workers was gone.

HusainPatel7 commented 2 months ago

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 am also experiencing the same issue. Please let me know if anyone has found a solution for it."

dyabol commented 2 months ago

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 am also experiencing the same issue. Please let me know if anyone has found a solution for it."

Try my solution here: https://github.com/firebase/firebase-js-sdk/issues/7693#issuecomment-2077118457