Skip to content

Commit 5e7fccd

Browse files
kevinfarrugiabsmth
andauthored
Improve reconnection logic for websocket example (#364)
* Improve reconnection logic for websocket example * Replace space with tabs --------- Co-authored-by: Brian Smith <brian@smith.berlin>
1 parent 9a8acd0 commit 5e7fccd

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

websockets/client.js

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,41 @@ function log(text) {
99
logElement.scrollTop = logElement.scrollHeight;
1010
}
1111

12-
// Open the websocket when the page is shown
13-
window.addEventListener("pageshow", () => {
14-
log("OPENING");
15-
16-
websocket = new WebSocket(wsUri);
17-
18-
websocket.addEventListener("open", () => {
12+
function initializeWebSocketListeners(ws) {
13+
ws.addEventListener("open", () => {
1914
log("CONNECTED");
2015
pingInterval = setInterval(() => {
2116
log(`SENT: ping: ${counter}`);
22-
websocket.send("ping");
17+
ws.send("ping");
2318
}, 1000);
2419
});
2520

26-
websocket.addEventListener("close", () => {
21+
ws.addEventListener("close", () => {
2722
log("DISCONNECTED");
2823
clearInterval(pingInterval);
2924
});
3025

31-
websocket.addEventListener("message", (e) => {
26+
ws.addEventListener("message", (e) => {
3227
log(`RECEIVED: ${e.data}: ${counter}`);
3328
counter++;
3429
});
3530

36-
websocket.addEventListener("error", (e) => {
37-
log(`ERROR: ${e.data}`);
31+
ws.addEventListener("error", (e) => {
32+
log(`ERROR`);
3833
});
34+
}
35+
36+
window.addEventListener("pageshow", (event) => {
37+
if (event.persisted) {
38+
websocket = new WebSocket(wsUri);
39+
initializeWebSocketListeners(websocket);
40+
}
3941
});
4042

43+
log("OPENING");
44+
websocket = new WebSocket(wsUri);
45+
initializeWebSocketListeners(websocket);
46+
4147
// Close the websocket when the user leaves.
4248
window.addEventListener("pagehide", () => {
4349
if (websocket) {

0 commit comments

Comments
 (0)