33
44class ServiceWorkerManager {
55 private registration : ServiceWorkerRegistration | null = null ;
6+ private pendingToken : string | null = null ;
67
78 async register ( ) : Promise < void > {
89 if ( ! ( 'serviceWorker' in navigator ) ) {
@@ -20,6 +21,15 @@ class ServiceWorkerManager {
2021 // Wait for the service worker to be ready
2122 await navigator . serviceWorker . ready ;
2223
24+ // Re-read registration because it may have changed during activation
25+ this . registration = await navigator . serviceWorker . getRegistration ( '/' ) || this . registration ;
26+
27+ // Send any queued token once the worker is active
28+ if ( this . pendingToken && this . registration ?. active ) {
29+ this . sendTokenToWorker ( this . pendingToken ) ;
30+ this . pendingToken = null ;
31+ }
32+
2333 // Set up message handling
2434 navigator . serviceWorker . addEventListener ( 'message' , this . handleMessage . bind ( this ) ) ;
2535
@@ -29,16 +39,25 @@ class ServiceWorkerManager {
2939 }
3040
3141 async setToken ( token : string ) : Promise < void > {
42+ if ( this . registration ?. active ) {
43+ this . sendTokenToWorker ( token ) ;
44+ return ;
45+ }
46+
47+ this . pendingToken = token ;
48+ console . log ( 'Service worker not active yet; token queued for delivery after registration' ) ;
49+ }
50+
51+ private sendTokenToWorker ( token : string ) : void {
3252 if ( ! this . registration ?. active ) {
3353 console . warn ( 'Service worker not active, cannot send token' ) ;
3454 return ;
3555 }
3656
3757 try {
38- // Send token to service worker for storage in IndexedDB
3958 this . registration . active . postMessage ( {
4059 type : 'SET_TOKEN' ,
41- token : token
60+ token
4261 } ) ;
4362
4463 console . log ( 'Token sent to service worker for secure storage' ) ;
0 commit comments