fix: MV3 SW keepalive for WS connection via periodic alarm ping

This commit is contained in:
Jiaqing Liang
2026-03-31 11:19:48 +08:00
parent 106c6b04f1
commit 86210296c1

View File

@@ -203,6 +203,11 @@ function scheduleProbe() {
chrome.alarms.create('tmwd-ws-probe', { delayInMinutes: 0.083 }); // ~5s chrome.alarms.create('tmwd-ws-probe', { delayInMinutes: 0.083 }); // ~5s
} }
function scheduleKeepalive() {
// Keep SW alive while WS is connected (~25s, under 30s SW timeout)
chrome.alarms.create('tmwd-ws-keepalive', { delayInMinutes: 0.4 }); // ~24s
}
async function isServerAlive() { async function isServerAlive() {
try { try {
const ctrl = new AbortController(); const ctrl = new AbortController();
@@ -215,6 +220,17 @@ async function isServerAlive() {
} }
chrome.alarms.onAlarm.addListener(async (alarm) => { chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'tmwd-ws-keepalive') {
// Keepalive: ping to keep SW alive + detect dead connections
if (ws && ws.readyState === WebSocket.OPEN) {
try { ws.send('{"type":"ping"}'); } catch (_) {}
scheduleKeepalive();
} else {
// Connection lost, switch to probe mode
ws = null;
scheduleProbe();
}
}
if (alarm.name === 'tmwd-ws-probe') { if (alarm.name === 'tmwd-ws-probe') {
if (ws && ws.readyState <= 1) return; // Already connected/connecting if (ws && ws.readyState <= 1) return; // Already connected/connecting
if (await isServerAlive()) { if (await isServerAlive()) {
@@ -240,7 +256,7 @@ function connectWS() {
} }
ws.onopen = async () => { ws.onopen = async () => {
console.log('[TMWD-WS] Connected!'); console.log('[TMWD-WS] Connected!');
chrome.alarms.clear('tmwd-ws-probe'); scheduleKeepalive(); // Keep SW alive while connected
const tabs = (await chrome.tabs.query({})).filter(t => isScriptable(t.url)); const tabs = (await chrome.tabs.query({})).filter(t => isScriptable(t.url));
ws.send(JSON.stringify({ ws.send(JSON.stringify({
type: 'ext_ready', type: 'ext_ready',