-
Notifications
You must be signed in to change notification settings - Fork 969
Description
[REQUIRED] Describe your environment
- Operating System version: Windows 10 Home 19043.1526
- Browser version: 98.0.4758.82 (Official Build) (64-bit)
- Firebase SDK version: ^9.0.0-beta.1
- Firebase Product: messaging
[REQUIRED] Describe the problem
Calling messaging getToken sometimes throws the error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
This occurs when a user has not yet registered the service worker i.e. it is their first visit to the web app or their first usage of a feature that involves the use of the service worker -> since getToken does not register the SW until that point.
It seems there may be a race condition where the service worker may or may not be ready when
const subscription = await swRegistration.pushManager.getSubscription();
is called here
const subscription = await swRegistration.pushManager.getSubscription(); |
Other online sources here https://stackoverflow.com/questions/42063006/failed-to-subscribe-the-user-domexception-subscription-failed-no-active-serv and here bradtraversy/node_push_notifications#1 (comment) seem to solve this issue with the line await navigator.serviceWorker.ready;
to wait for the service worker to be ready,
This may be connected to issue 5797 here #5797.
Steps to reproduce:
Caveat: in most cases the steps below will not trigger the issue, it will only occur when the service worker is not ready
- Clear cache & remove notification permission
- 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> })
Relevant Code:
const supported = await isSupported()
if (!supported) {
throw new Error(NOTIFICATIONS_NOT_SUPPORTED)
}
const messaging = getMessaging();
const messagingToken = await getToken(messaging, {vapidKey})