// Reports tabs that play audio to moonmix-tabs-host: id, title and whether // they are audible now. Tabs that never made a sound, page addresses and // incognito tabs are never sent. const HOST = "org.latha.moonmix.tabs"; const RETRY_MS = 5000; // Tabs heard since the host connected. An open native port keeps this worker // alive, so nothing needs to be stored. const heard = new Map(); let port = null; let retry = null; function send() { port?.postMessage({ tabs: [...heard.values()] }); } // True if what we would send changed. function note(tab) { if (tab.id === undefined || tab.incognito) return false; const old = heard.get(tab.id); if (!old && !tab.audible) return false; const now = { id: tab.id, title: tab.title ?? "", audible: !!tab.audible }; if (old && old.title === now.title && old.audible === now.audible) return false; heard.set(tab.id, now); return true; } async function connect() { if (port) return; clearTimeout(retry); const opened = chrome.runtime.connectNative(HOST); port = opened; opened.onDisconnect.addListener(() => { // Not installed, or PipeWire went away. lastError must be read. void chrome.runtime.lastError; if (port !== opened) return; port = null; retry = setTimeout(connect, RETRY_MS); }); heard.clear(); for (const tab of await chrome.tabs.query({ audible: true })) note(tab); send(); } chrome.tabs.onUpdated.addListener((_id, change, tab) => { if (!port) connect(); else if (("audible" in change || "title" in change) && note(tab)) send(); }); chrome.tabs.onRemoved.addListener((id) => { if (heard.delete(id)) send(); }); // Prerendered or discarded tabs can come back with another id. chrome.tabs.onReplaced.addListener(async (added, removed) => { let changed = heard.delete(removed); try { changed = note(await chrome.tabs.get(added)) || changed; } catch { // Already closed. } if (changed) send(); }); chrome.runtime.onStartup.addListener(connect); chrome.runtime.onInstalled.addListener(connect); connect();