fix: WS reconnect on foreground, visibility change listener

This commit is contained in:
2026-07-27 19:15:32 +08:00
parent 4becc26e45
commit 5bc2c18f06
+16 -2
View File
@@ -5,15 +5,26 @@ const WS = {
_reconnectDelay: 2000, _reconnectDelay: 2000,
_handlers: {}, _handlers: {},
_connected: false, _connected: false,
_lastPong: 0,
init() { init() {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
this._url = `${protocol}//${location.host}/ws`; this._url = `${protocol}//${location.host}/ws`;
this._connect(); 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() { _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 { try {
this._ws = new WebSocket(this._url); this._ws = new WebSocket(this._url);
@@ -24,6 +35,7 @@ const WS = {
this._ws.onopen = () => { this._ws.onopen = () => {
this._connected = true; this._connected = true;
this._lastPong = Date.now();
this._reconnectDelay = 2000; this._reconnectDelay = 2000;
this._emit('connection', true); this._emit('connection', true);
this._emit('status', 'connected'); this._emit('status', 'connected');
@@ -32,6 +44,7 @@ const WS = {
this._ws.onmessage = (event) => { this._ws.onmessage = (event) => {
try { try {
const msg = JSON.parse(event.data); const msg = JSON.parse(event.data);
if (msg.type === 'pong') { this._lastPong = Date.now(); return; }
this._emit(msg.type || 'message', msg.data || msg); this._emit(msg.type || 'message', msg.data || msg);
if (msg.type === 'telemetry') { if (msg.type === 'telemetry') {
this._emit('telemetry', msg.data); this._emit('telemetry', msg.data);
@@ -47,7 +60,8 @@ const WS = {
}; };
this._ws.onerror = () => { this._ws.onerror = () => {
this._emit('status', 'error'); this._emit('status', 'disconnected');
this._connected = false;
}; };
}, },