@@ -16,20 +16,33 @@ const useServiceWorkerRegistration = (service?: string) => {
1616 console . warn ( 'ServiceWorker API exists but register() is not available.' ) ;
1717 return ;
1818 }
19- const shouldInstallServiceWorker =
20- onClient ( ) && 'serviceWorker' in navigator ;
2119
22- if ( shouldInstallServiceWorker ) {
23- // Scope option to ensure the service worker only controls pages under /{service}
24- const result = sw . register ( `/ ${ service } /sw.js` , {
25- scope : `/${ service } ` ,
26- } ) ;
20+ const cleanupLegacyRegistrations = async ( ) => {
21+ const registrations = await sw . getRegistrations ( ) ;
22+ const legacy = registrations . find (
23+ reg => new URL ( reg . scope ) . pathname === `/${ service } / ` ,
24+ ) ;
2725
28- Promise . resolve ( result ) . catch ( err => {
26+ if ( legacy ) {
2927 // eslint-disable-next-line no-console
30- console . error ( 'Service worker registration failed:' , err ) ;
28+ console . log (
29+ `📌 Cleaned up legacy service worker registration for /${ service } /` ,
30+ ) ;
31+ await legacy . unregister ( ) ;
32+ }
33+ } ;
34+ const initializeServiceWorker = async ( ) => {
35+ await cleanupLegacyRegistrations ( ) ;
36+
37+ return sw . register ( `/${ service } /sw.js` , {
38+ scope : `/${ service } ` ,
3139 } ) ;
32- }
40+ } ;
41+
42+ initializeServiceWorker ( ) . catch ( err => {
43+ // eslint-disable-next-line no-console
44+ console . error ( 'Service worker initialization failed:' , err ) ;
45+ } ) ;
3346 } , [ service ] ) ;
3447} ;
3548
0 commit comments