Skip to content

Commit 8a2f5a3

Browse files
fix(eio-client): move 'offline' event listener at the top
Related: #5125
1 parent b04fa64 commit 8a2f5a3

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

packages/engine.io-client/lib/socket.ts

+25-2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ const withEventListeners =
2020
typeof addEventListener === "function" &&
2121
typeof removeEventListener === "function";
2222

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+
2341
export interface SocketOptions {
2442
/**
2543
* The host that we're connecting to. Set from the URI passed when connecting
@@ -448,12 +466,13 @@ export class SocketWithoutUpgrade extends Emitter<
448466
);
449467
}
450468
if (this.hostname !== "localhost") {
469+
debug("adding listener for the 'offline' event");
451470
this._offlineEventListener = () => {
452471
this._onClose("transport close", {
453472
description: "network connection lost",
454473
});
455474
};
456-
addEventListener("offline", this._offlineEventListener, false);
475+
OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
457476
}
458477
}
459478

@@ -916,7 +935,11 @@ export class SocketWithoutUpgrade extends Emitter<
916935
);
917936
}
918937
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+
}
920943
}
921944
}
922945

0 commit comments

Comments
 (0)