document.addEventListener('DOMContentLoaded', function () { const toggle = document.getElementById('toggle'); const syncSystem = document.getElementById('syncSystem'); const status = document.getElementById('status'); // Get active tab to determine site key chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { const tab = tabs[0]; if (!tab) return; // Extract hostname or use url as key let siteKey; try { const url = new URL(tab.url); siteKey = url.hostname; if (!siteKey) siteKey = tab.url; } catch (e) { siteKey = tab.url; } // Load saved state chrome.storage.sync.get([siteKey, 'syncWithSystem'], function (result) { toggle.checked = result[siteKey] === true; syncSystem.checked = result.syncWithSystem === true; }); // Check current tab state (for UI hint only) chrome.tabs.sendMessage(tab.id, { action: "checkState" }, function (response) { if (chrome.runtime.lastError) { status.textContent = "Try refreshing the page."; toggle.disabled = true; return; } if (response && response.isDark) { status.textContent = "Site appears dark."; } else { status.textContent = ""; } }); function notifyContentScript() { const enabled = toggle.checked; const sync = syncSystem.checked; // Save state const saveObj = { syncWithSystem: sync }; saveObj[siteKey] = enabled; chrome.storage.sync.set(saveObj); // Notify active tab chrome.tabs.sendMessage(tab.id, { action: "updateConfig", siteEnabled: enabled, syncWithSystem: sync }); } // Handle changes toggle.addEventListener('change', notifyContentScript); syncSystem.addEventListener('change', notifyContentScript); }); });