Skip to content

Commit

Permalink
Correctly wait for service worker registration to become active befor…
Browse files Browse the repository at this point in the history
…e allowing any operations on it.
  • Loading branch information
hsubox76 committed Dec 2, 2024
1 parent ffbf5a6 commit 2035fe8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/neat-beans-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@firebase/messaging': patch
---

Fix an issue where PushManager.subscribe() is called too soon after registering the default service worker.
31 changes: 31 additions & 0 deletions packages/messaging/src/helpers/registerDefaultSw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,40 @@ export async function registerDefaultSw(
messaging.swRegistration.update().catch(() => {
/* it is non blocking and we don't care if it failed */
});
await waitForRegistrationActive(messaging.swRegistration);
} catch (e) {
throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {
browserErrorMessage: (e as Error)?.message
});
}
}

/**
* Waits for registration to become active. MDN documentation claims that
* a service worker registration should be ready to use after awaiting
* navigator.serviceWorker.register() but that doesn't seem to be the case in
* practice, causing the SDK to throw errors when calling
* swRegistration.pushManager.subscribe() too soon after register(). The only
* solution seems to be waiting for the service worker registration `state`
* to become "active".
*/
async function waitForRegistrationActive(
registration: ServiceWorkerRegistration
): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (registration.active) {
resolve();
}
const incomingSw = registration.installing || registration.waiting;
if (incomingSw) {
incomingSw.onstatechange = ev => {
if ((ev.target as ServiceWorker)?.state === 'activated') {
incomingSw.onstatechange = null;
resolve();
}
};
} else {
reject(new Error('No incoming service worker found.'));
}
});
}

0 comments on commit 2035fe8

Please sign in to comment.