80 lines
2.2 KiB
JavaScript
80 lines
2.2 KiB
JavaScript
(function (root) {
|
|
"use strict";
|
|
|
|
function createBackgroundController(api) {
|
|
const tabStates = new Map();
|
|
|
|
function validTabId(tabId) {
|
|
return Number.isInteger(tabId) && tabId >= 0;
|
|
}
|
|
|
|
async function broadcast(tabId, enabled) {
|
|
try {
|
|
await api.tabs.sendMessage(tabId, {
|
|
type: "glagolify:set-enabled",
|
|
enabled
|
|
});
|
|
return true;
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
api.runtime.onMessage.addListener((message, sender) => {
|
|
if (!message || typeof message.type !== "string") {
|
|
return undefined;
|
|
}
|
|
|
|
if (message.type === "glagolify:document-ready") {
|
|
const tabId = sender && sender.tab && sender.tab.id;
|
|
return Promise.resolve({
|
|
enabled: validTabId(tabId) && tabStates.get(tabId) === true
|
|
});
|
|
}
|
|
|
|
if (message.type === "glagolify:get-tab-state") {
|
|
const tabId = message.tabId;
|
|
if (!validTabId(tabId)) {
|
|
return Promise.resolve({ enabled: false, available: false });
|
|
}
|
|
|
|
const enabled = tabStates.get(tabId) === true;
|
|
return broadcast(tabId, enabled).then((available) => ({ enabled, available }));
|
|
}
|
|
|
|
if (message.type === "glagolify:set-tab-enabled") {
|
|
const tabId = message.tabId;
|
|
if (!validTabId(tabId) || typeof message.enabled !== "boolean") {
|
|
return Promise.resolve({ enabled: false, available: false });
|
|
}
|
|
|
|
tabStates.set(tabId, message.enabled);
|
|
return broadcast(tabId, message.enabled).then((available) => ({
|
|
enabled: message.enabled,
|
|
available
|
|
}));
|
|
}
|
|
|
|
return undefined;
|
|
});
|
|
|
|
api.tabs.onRemoved.addListener((tabId) => {
|
|
tabStates.delete(tabId);
|
|
});
|
|
|
|
return { tabStates, broadcast };
|
|
}
|
|
|
|
const exported = Object.freeze({ createBackgroundController });
|
|
|
|
if (typeof browser === "object" && browser.runtime && browser.tabs) {
|
|
createBackgroundController(browser);
|
|
}
|
|
|
|
if (typeof module === "object" && module.exports) {
|
|
module.exports = exported;
|
|
}
|
|
|
|
root.GlagolifyBackground = exported;
|
|
})(typeof globalThis === "object" ? globalThis : this);
|