Skip to content

Commit b15bddf

Browse files
arturovtatscott
authored andcommitted
fix(service-worker): do not register service worker if app is destroyed before it is ready to register (#61101)
In this commit, we check whether the application is destroyed before calling `serviceWorker.register(...)`. We should not register the worker because other resources will not be available. PR Close #61101
1 parent 5f1bd07 commit b15bddf

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

packages/service-worker/src/provider.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,14 @@ export function ngswAppInitializer(): void {
9292

9393
// Don't return anything to avoid blocking the application until the SW is registered.
9494
// Catch and log the error if SW registration fails to avoid uncaught rejection warning.
95-
readyToRegister.then(() =>
95+
readyToRegister.then(() => {
96+
// If the registration strategy has resolved after the application has
97+
// been explicitly destroyed by the user (e.g., by navigating away to
98+
// another application), we simply should not register the worker.
99+
if (appRef.destroyed) {
100+
return;
101+
}
102+
96103
navigator.serviceWorker
97104
.register(script, {scope: options.scope})
98105
.catch((err) =>
@@ -103,8 +110,8 @@ export function ngswAppInitializer(): void {
103110
'Service worker registration failed with: ' + err,
104111
),
105112
),
106-
),
107-
);
113+
);
114+
});
108115
});
109116
}
110117

packages/service-worker/test/provider_spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,17 @@ async function waitForReadyToRegister() {
364364
);
365365
expect(swRegisterSpy).not.toHaveBeenCalled();
366366
});
367+
368+
it('should not register service worker if app was destroyed before it was ready to register', async () => {
369+
const registerSub = new Subject<void>();
370+
configTestBedWithMockedStability(() => registerSub);
371+
expect(swRegisterSpy).not.toHaveBeenCalled();
372+
// Given that the app is destroyed (e.g., by calling `ApplicationRef.destroy()`)
373+
// before the `readyToRegister` promise resolves and `serviceWorker.register(...)` is called.
374+
TestBed.resetTestingModule();
375+
await waitForReadyToRegister();
376+
expect(swRegisterSpy).not.toHaveBeenCalled();
377+
});
367378
});
368379
});
369380
});

0 commit comments

Comments
 (0)