Skip to content

Commit 7c31547

Browse files
committed
fix: close WebSocket on pagehide to support bfcache
1 parent 2d3c81e commit 7c31547

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

packages/javascript/src/modules/socket.ts

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ export default class Socket implements Transport {
5454
*/
5555
private reconnectionAttempts: number;
5656

57+
/**
58+
* Page hide event handler reference (for removal)
59+
*/
60+
private pageHideHandler: () => void;
61+
5762
/**
5863
* Creates new Socket instance. Setup initial socket params.
5964
*
@@ -77,6 +82,11 @@ export default class Socket implements Transport {
7782
this.reconnectionTimeout = reconnectionTimeout;
7883
this.reconnectionAttempts = reconnectionAttempts;
7984

85+
this.pageHideHandler = () => {
86+
log('Page entering bfcache, closing WebSocket', 'info');
87+
this.close();
88+
};
89+
8090
this.eventsQueue = [];
8191
this.ws = null;
8292

@@ -120,12 +130,25 @@ export default class Socket implements Transport {
120130
}
121131

122132
/**
123-
* Create new WebSocket connection and setup event listeners
133+
* Setup window event listeners
134+
*/
135+
private setupListeners(): void {
136+
window.addEventListener('pagehide', this.pageHideHandler, { capture: true });
137+
}
138+
139+
/**
140+
* Remove window event listeners
141+
*/
142+
public destroyListeners(): void {
143+
window.removeEventListener('pagehide', this.pageHideHandler, { capture: true });
144+
}
145+
146+
/**
147+
* Create new WebSocket connection and setup socket event listeners
124148
*/
125149
private init(): Promise<void> {
126150
return new Promise((resolve, reject) => {
127151
this.ws = new WebSocket(this.url);
128-
129152
/**
130153
* New message handler
131154
*/
@@ -139,6 +162,8 @@ export default class Socket implements Transport {
139162
* @param event - websocket event on closing
140163
*/
141164
this.ws.onclose = (event: CloseEvent): void => {
165+
this.destroyListeners();
166+
142167
if (typeof this.onClose === 'function') {
143168
this.onClose(event);
144169
}
@@ -154,6 +179,8 @@ export default class Socket implements Transport {
154179
};
155180

156181
this.ws.onopen = (event: Event): void => {
182+
this.setupListeners();
183+
157184
if (typeof this.onOpen === 'function') {
158185
this.onOpen(event);
159186
}
@@ -163,6 +190,16 @@ export default class Socket implements Transport {
163190
});
164191
}
165192

193+
/**
194+
* Closes socket, it can be restored with init() later
195+
*/
196+
private close(): void {
197+
if (this.ws) {
198+
this.ws.close();
199+
this.ws = null;
200+
}
201+
}
202+
166203
/**
167204
* Tries to reconnect to the server for specified number of times with the interval
168205
*

0 commit comments

Comments
 (0)