Skip to content

Commit

Permalink
Avoid auto-disconnect when inactive (#318)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Jul 6, 2024
1 parent 3fb653e commit 7456044
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion source/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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}) {
Expand Down

0 comments on commit 7456044

Please sign in to comment.