From db6d89988d66dde98a9f7ec51a33f11e4232131f Mon Sep 17 00:00:00 2001 From: Federico Date: Sat, 6 Jul 2024 16:30:45 +0800 Subject: [PATCH] Send keep-alive message --- source/background.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/source/background.js b/source/background.js index 3d3d544..f524c77 100644 --- a/source/background.js +++ b/source/background.js @@ -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}) {