Skip to content

Commit 99925a4

Browse files
fix: properly clear "beforeunload" event listener
Related: #693
1 parent d4d6463 commit 99925a4

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

lib/socket.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,8 @@ export class Socket extends Emitter<{}, {}, SocketReservedEvents> {
248248
private pingTimeoutTimer: NodeJS.Timer;
249249
private setTimeoutFn: typeof setTimeout;
250250
private clearTimeoutFn: typeof clearTimeout;
251-
private offlineEventListener;
251+
private readonly beforeunloadEventListener: () => void;
252+
private readonly offlineEventListener: () => void;
252253
private upgrading: boolean;
253254
private maxPayload?: number;
254255

@@ -352,17 +353,14 @@ export class Socket extends Emitter<{}, {}, SocketReservedEvents> {
352353
// Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
353354
// ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
354355
// closed/reloaded)
355-
addEventListener(
356-
"beforeunload",
357-
() => {
358-
if (this.transport) {
359-
// silently close the transport
360-
this.transport.removeAllListeners();
361-
this.transport.close();
362-
}
363-
},
364-
false
365-
);
356+
this.beforeunloadEventListener = () => {
357+
if (this.transport) {
358+
// silently close the transport
359+
this.transport.removeAllListeners();
360+
this.transport.close();
361+
}
362+
};
363+
addEventListener("beforeunload", this.beforeunloadEventListener, false);
366364
}
367365
if (this.hostname !== "localhost") {
368366
this.offlineEventListener = () => {
@@ -912,6 +910,11 @@ export class Socket extends Emitter<{}, {}, SocketReservedEvents> {
912910
this.transport.removeAllListeners();
913911

914912
if (typeof removeEventListener === "function") {
913+
removeEventListener(
914+
"beforeunload",
915+
this.beforeunloadEventListener,
916+
false
917+
);
915918
removeEventListener("offline", this.offlineEventListener, false);
916919
}
917920

0 commit comments

Comments
 (0)