Closed
Description
[REQUIRED] Describe your environment
- Operating System version: MacOS 12.0.1
- Browser version: Chrome Version 96.0.4664.55 (Official Build) (x86_64)
- Firebase SDK version: 9.5.0
- Firebase Product: messaging
[REQUIRED] Describe the problem
Sometimes calling messaging getToken returns the error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
. It seems to only occur on the first page load, when the user refreshes the notifications work and there's no error anymore.
Steps to reproduce:
- Add
firebase-messaging-sw.js
to root of domain - Call firebase initializeApp
- Call firebase getMessaging
- Ask and approve browser notification permission
- Add firebase onMessage listener
- Call firebase
await getToken(messaging, { vapidKey: <VAPID_KEY> })
Error sometimes appears with Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
Relevant Code:
firebase-messaging-sw.js
is at the root of project and firebase gets initialised right away:
import { initializeApp } from 'firebase/app';
import { getMessaging, isSupported, Messaging } from 'firebase/messaging';
isSupported()
.then((supported) => {
if (supported) {
initializeApp(firebaseConfig);
messaging = getMessaging();
} else {
console.error('Browser does not support notifications');
}
})
const registerToken = async (
messaging: Messaging
): Promise<{ token?: string; error?: unknown }> => {
try {
const currentToken = await getToken(messaging, {
vapidKey: <VAPID_KEY>,
});
// server call with token
await api.registerToken(currentToken);
return { token: currentToken };
} catch (error) {
// Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
return { error };
}
};
Since firebase handles registering firebase-messaging-sw.js
itself, I had a look at the codebase, and it seems the issue originates from: