firebase-js-sdk icon indicating copy to clipboard operation
firebase-js-sdk copied to clipboard

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

Open 2manoj1 opened this issue 1 year ago • 57 comments

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

  • 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

2manoj1 avatar Aug 21 '23 08:08 2manoj1

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

2manoj1 avatar Aug 21 '23 08:08 2manoj1

Screenshot 2023-08-21 at 2 23 42 PM

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

2manoj1 avatar Aug 21 '23 08:08 2manoj1

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.

jbalidiong avatar Aug 21 '23 14:08 jbalidiong

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

2manoj1 avatar Aug 22 '23 18:08 2manoj1

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

2manoj1 avatar Aug 25 '23 10:08 2manoj1

@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 avatar Aug 25 '23 15:08 jbalidiong

@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

2manoj1 avatar Aug 25 '23 20:08 2manoj1

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 avatar Aug 30 '23 20:08 zwu52

@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

2manoj1 avatar Aug 30 '23 21:08 2manoj1

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?

zwu52 avatar Aug 31 '23 18:08 zwu52

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

2manoj1 avatar Aug 31 '23 19:08 2manoj1

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

2manoj1 avatar Sep 04 '23 07:09 2manoj1

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.

kessler428 avatar Sep 07 '23 07:09 kessler428

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

2manoj1 avatar Sep 08 '23 13:09 2manoj1

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

dpeese avatar Oct 26 '23 16:10 dpeese

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?

FarzaneGhb avatar Nov 25 '23 06:11 FarzaneGhb

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.

mohamedamara1 avatar Dec 13 '23 20:12 mohamedamara1

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

OHoussein avatar Dec 20 '23 15:12 OHoussein

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

leoalassia avatar Jan 09 '24 23:01 leoalassia

Same issue here with Flutter 3.16

LostInDarkMath avatar Jan 16 '24 06:01 LostInDarkMath

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!

ben-xx avatar Jan 17 '24 22:01 ben-xx

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

gagjunior avatar Jan 30 '24 00:01 gagjunior

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

MartinDapper avatar Feb 06 '24 18:02 MartinDapper

I'm facing the same issue

ps011 avatar Feb 11 '24 21:02 ps011

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

ascorbic-acid avatar Feb 22 '24 06:02 ascorbic-acid

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 avatar Feb 27 '24 15:02 arc-prvh

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 avatar Feb 27 '24 19:02 arc-prvh

@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

2manoj1 avatar Feb 27 '24 23:02 2manoj1

No solution for this issue?

dab246 avatar Mar 29 '24 11:03 dab246

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

arc-prvh avatar Mar 29 '24 15:03 arc-prvh