From 5bc2c18f067ddc3081279d9824c5e386dd57a2bd Mon Sep 17 00:00:00 2001 From: AskaEth Date: Mon, 27 Jul 2026 19:15:32 +0800 Subject: [PATCH] fix: WS reconnect on foreground, visibility change listener --- static/js/ws.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/static/js/ws.js b/static/js/ws.js index e1eaa80..5212522 100644 --- a/static/js/ws.js +++ b/static/js/ws.js @@ -5,15 +5,26 @@ const WS = { _reconnectDelay: 2000, _handlers: {}, _connected: false, + _lastPong: 0, init() { const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; this._url = `${protocol}//${location.host}/ws`; this._connect(); + + document.addEventListener('visibilitychange', () => { + if (!document.hidden && !this._connected) { + this._reconnectDelay = 500; + this._connect(); + } + if (!document.hidden && this._connected) { + this.send({type: 'ping'}); + } + }); }, _connect() { - if (this._ws && this._ws.readyState === WebSocket.OPEN) return; + if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) return; try { this._ws = new WebSocket(this._url); @@ -24,6 +35,7 @@ const WS = { this._ws.onopen = () => { this._connected = true; + this._lastPong = Date.now(); this._reconnectDelay = 2000; this._emit('connection', true); this._emit('status', 'connected'); @@ -32,6 +44,7 @@ const WS = { this._ws.onmessage = (event) => { try { const msg = JSON.parse(event.data); + if (msg.type === 'pong') { this._lastPong = Date.now(); return; } this._emit(msg.type || 'message', msg.data || msg); if (msg.type === 'telemetry') { this._emit('telemetry', msg.data); @@ -47,7 +60,8 @@ const WS = { }; this._ws.onerror = () => { - this._emit('status', 'error'); + this._emit('status', 'disconnected'); + this._connected = false; }; },