fix: WS reconnect on foreground, visibility change listener
This commit is contained in:
+16
-2
@@ -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;
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user