@@ -20,6 +20,24 @@ const withEventListeners =
20
20
typeof addEventListener === "function" &&
21
21
typeof removeEventListener === "function" ;
22
22
23
+ const OFFLINE_EVENT_LISTENERS = [ ] ;
24
+
25
+ if ( withEventListeners ) {
26
+ // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
27
+ // script, so we create one single event listener here which will forward the event to the socket instances
28
+ addEventListener (
29
+ "offline" ,
30
+ ( ) => {
31
+ debug (
32
+ "closing %d connection(s) because the network was lost" ,
33
+ OFFLINE_EVENT_LISTENERS . length ,
34
+ ) ;
35
+ OFFLINE_EVENT_LISTENERS . forEach ( ( listener ) => listener ( ) ) ;
36
+ } ,
37
+ false ,
38
+ ) ;
39
+ }
40
+
23
41
export interface SocketOptions {
24
42
/**
25
43
* The host that we're connecting to. Set from the URI passed when connecting
@@ -448,12 +466,13 @@ export class SocketWithoutUpgrade extends Emitter<
448
466
) ;
449
467
}
450
468
if ( this . hostname !== "localhost" ) {
469
+ debug ( "adding listener for the 'offline' event" ) ;
451
470
this . _offlineEventListener = ( ) => {
452
471
this . _onClose ( "transport close" , {
453
472
description : "network connection lost" ,
454
473
} ) ;
455
474
} ;
456
- addEventListener ( "offline" , this . _offlineEventListener , false ) ;
475
+ OFFLINE_EVENT_LISTENERS . push ( this . _offlineEventListener ) ;
457
476
}
458
477
}
459
478
@@ -916,7 +935,11 @@ export class SocketWithoutUpgrade extends Emitter<
916
935
) ;
917
936
}
918
937
if ( this . _offlineEventListener ) {
919
- removeEventListener ( "offline" , this . _offlineEventListener , false ) ;
938
+ const i = OFFLINE_EVENT_LISTENERS . indexOf ( this . _offlineEventListener ) ;
939
+ if ( i !== - 1 ) {
940
+ debug ( "removing listener for the 'offline' event" ) ;
941
+ OFFLINE_EVENT_LISTENERS . splice ( i , 1 ) ;
942
+ }
920
943
}
921
944
}
922
945
0 commit comments