LiveOverlayExtension/background.js
TristanEDU 638f14d174 feat: add proper toggle functionality with per-tab overlay injection and cleanup
- Replaced automatic content script injection with manual toggle via extension icon
- Implemented background service worker to inject or remove overlay on click
- Ensures overlay iframe and control panel are fully removed when toggled off
- Prevents duplicate overlays by checking for existing elements
- Added icon support for active/inactive state in the toolbar
- Now supports per-tab activation with isolated overlay control
2025-05-30 14:00:51 -07:00

35 lines
1.1 KiB
JavaScript

const tabOverlayStatus = {};
chrome.action.onClicked.addListener(async (tab) => {
const tabId = tab.id;
// First, always attempt to remove any existing overlay from this tab
chrome.scripting.executeScript({
target: { tabId },
func: () => {
const iframe = document.getElementById("overlay-iframe");
const controls = Array.from(document.querySelectorAll("div")).find(
(el) =>
el.textContent?.includes("Overlay Controls") &&
el.style?.position === "fixed"
);
if (iframe) iframe.remove();
if (controls) controls.remove();
},
});
// If the overlay was already active, we just removed it above
if (tabOverlayStatus[tabId]) {
tabOverlayStatus[tabId] = false;
chrome.action.setIcon({ tabId, path: "icon-off.png" }); // optional
} else {
// If not active, inject the overlay
chrome.scripting.executeScript({
target: { tabId },
files: ["content.js"],
});
tabOverlayStatus[tabId] = true;
chrome.action.setIcon({ tabId, path: "icon-on.png" }); // optional
}
});