Avoid auto-disconnect when inactive (#318)

This commit is contained in:
Federico Brigante 2024-07-06 16:38:08 +08:00 committed by GitHub
parent 3fb653eea1
commit 745604460d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -97,12 +97,17 @@ chrome.runtime.onConnect.addListener(handlePortListenerErrors(async port => {
console.log('will open socket');
const socket = new WebSocket('ws://localhost:' + WebSocketPort);
let interval; // eslint-disable-line prefer-const -- Ur rong
await Promise.race([
oneEvent(socket, 'open'),
oneEvent(socket, 'error'),
]);
const onSocketClose = () => port.postMessage({close: true});
const onSocketClose = () => {
port.postMessage({close: true});
clearInterval(interval);
};
socket.addEventListener('close', onSocketClose);
socket.addEventListener('message', event => port.postMessage({message: event.data}));
socket.addEventListener('error', event => console.error('error!', event));
@ -114,8 +119,15 @@ chrome.runtime.onConnect.addListener(handlePortListenerErrors(async port => {
port.onDisconnect.addListener(() => {
socket.removeEventListener('close', onSocketClose);
socket.close();
clearInterval(interval);
});
port.postMessage({ready: true});
interval = setInterval(() => {
// Keep-alive for MV3 https://github.com/fregante/GhostText/issues/317
port.postMessage({ping: true});
console.log('ping');
}, 5000);
}));
function handleMessages({code, count}, {tab}) {