Skip to content

Commit 9b3c9ab

Browse files
fix(eio-client): only remove the event listener if it exists
Related: #5088 (comment)
1 parent 043b55c commit 9b3c9ab

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

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

+16-8
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ import debugModule from "debug"; // debug()
1616

1717
const debug = debugModule("engine.io-client:socket"); // debug()
1818

19+
const withEventListeners =
20+
typeof addEventListener === "function" &&
21+
typeof removeEventListener === "function";
22+
1923
export interface SocketOptions {
2024
/**
2125
* The host that we're connecting to. Set from the URI passed when connecting
@@ -425,7 +429,7 @@ export class SocketWithoutUpgrade extends Emitter<
425429
this.opts.query = decode(this.opts.query);
426430
}
427431

428-
if (typeof addEventListener === "function") {
432+
if (withEventListeners) {
429433
if (this.opts.closeOnBeforeunload) {
430434
// Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
431435
// ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
@@ -903,13 +907,17 @@ export class SocketWithoutUpgrade extends Emitter<
903907
// ignore further transport communication
904908
this.transport.removeAllListeners();
905909

906-
if (typeof removeEventListener === "function") {
907-
removeEventListener(
908-
"beforeunload",
909-
this._beforeunloadEventListener,
910-
false,
911-
);
912-
removeEventListener("offline", this._offlineEventListener, false);
910+
if (withEventListeners) {
911+
if (this._beforeunloadEventListener) {
912+
removeEventListener(
913+
"beforeunload",
914+
this._beforeunloadEventListener,
915+
false,
916+
);
917+
}
918+
if (this._offlineEventListener) {
919+
removeEventListener("offline", this._offlineEventListener, false);
920+
}
913921
}
914922

915923
// set ready state

0 commit comments

Comments
 (0)