metamorpov/src/background.js

89 lines
2.5 KiB
JavaScript

let colorScheme = "light";
let state = "neutral";
/* Update the extension's icon by color scheme and state */
function updateIcon(event) {
browser.action.setIcon({
path: {
16: "icons/" + colorScheme + "-state-" + state + "-16x.png",
32: "icons/" + colorScheme + "-state-" + state + "-32x.png",
48: "icons/" + colorScheme + "-state-" + state + "-48x.png",
64: "icons/" + colorScheme + "-state-" + state + "-64x.png",
96: "icons/" + colorScheme + "-state-" + state + "-96x.png",
128: "icons/" + colorScheme + "-state-" + state + "-128x.png"
},
});
}
/* Listen for color scheme changes */
browser.runtime.onInstalled.addListener(updateColorSchemeOnInstall);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateColorScheme);
/* Update the color scheme to light or dark */
function updateColorScheme(event) {
const isDark = event.matches;
if (isDark) {
colorScheme = "dark";
} else {
colorScheme = "light";
}
updateIcon();
}
/* Updatw the color scheme on install */
function updateColorSchemeOnInstall() {
updateColorScheme(window.matchMedia('(prefers-color-scheme: dark)'));
}
/* Listen for tab changes */
window.addEventListener("load", updateState());
browser.tabs.onUpdated.addListener(updateStateOnReload, {urls: ["*://*/*"]});
browser.tabs.onActivated.addListener(updateState);
/* Update whether the extension is enabled for a host */
function updateState() {
let tabs = browser.tabs.query({ active: true, currentWindow: true });
tabs.then((tabs) => {
const tab = tabs[0];
const url = new URL(tab.url);
const isAllowedProtocol = url.protocol == "https:" || url.protocol == "http:";
if (!isAllowedProtocol) {
state = "neutral";
updateIcon();
return;
}
let storage = browser.storage.local.get("domains");
storage.then((storage) => {
const hostname = url.host;
const domains = storage.domains;
if (domains === undefined) {
state = "disabled";
}
else if (domains.includes(hostname)) {
state = "enabled";
} else {
state = "disabled";
}
}, logError).then(() => {
updateIcon();
}, logError);
}, logError);
}
/* Only update the state if the page was reloaded */
function updateStateOnReload(tabIs, changeInfo, tab) {
if (changeInfo.url && tab.url.host === changeInfo.url.host) {
return;
} else {
updateState();
}
}
/* Required by then */
function logError(error) {
console.log(`Error: ${error}`);
}