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
This commit is contained in:
TristanEDU 2025-05-30 14:00:51 -07:00
parent a34b719eaf
commit 638f14d174
4 changed files with 25 additions and 15 deletions

View File

@ -3,25 +3,29 @@ 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]) {
// Already injected → remove overlay
chrome.scripting.executeScript({
target: { tabId: tabId },
func: () => {
const iframe = document.getElementById("overlay-iframe");
const panel = document.querySelector(
'div[style*="Overlay Controls"]'
)?.parentElement;
if (iframe) iframe.remove();
if (panel) panel.remove();
},
});
tabOverlayStatus[tabId] = false;
chrome.action.setIcon({ tabId, path: "icon-off.png" }); // optional
} else {
// Not injected → inject content.js
// If not active, inject the overlay
chrome.scripting.executeScript({
target: { tabId: tabId },
target: { tabId },
files: ["content.js"],
});
tabOverlayStatus[tabId] = true;

View File

@ -6,7 +6,13 @@
"permissions": ["scripting", "activeTab", "tabs", "storage"],
"host_permissions": ["<all_urls>"],
"action": {
"default_title": "Toggle Overlay"
"default_title": "Toggle Overlay",
"default_icon": {
"16": "icon-on.png",
"32": "icon-on.png",
"48": "icon-on.png",
"128": "icon-on.png"
}
},
"background": {
"service_worker": "background.js"