-
Notifications
You must be signed in to change notification settings - Fork 7
/
background.js
65 lines (55 loc) · 2.33 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { supportedDomains, cloakablePatterns } from "./common.js";
// Get the current state of the extension from storage and update the badge
function getCurrentStateFromStorageAndUpdateBadge() {
// Check the current state of the extension and cloak the text accordingly
chrome.storage.sync.get().then(async (currentState) => {
chrome.tabs.query({ currentWindow: true, active: true }, async (tabs) => {
if (tabs[0] && tabs[0].url) {
const tabId = tabs[0].id;
const enabled = Object.values(currentState).some((value) => !!value);
// Set the badge text, color and tooltip
await chrome.action.setBadgeText({
tabId: tabId,
text: enabled ? "ON" : "OFF"
});
await chrome.action.setBadgeBackgroundColor({
tabId: tabId,
color: enabled ? "#00FF00" : "#FF0000"
});
}
});
});
}
// Inject the cloak script into the current tab/iframes
async function injectScripts(tabId, frameIds, allFrames) {
allFrames = false;
await chrome.scripting.executeScript({
target: { tabId, allFrames, frameIds },
files: ['cloak.js']
});
}
// This event is triggered when navigation occurs, which can include loading iframes
chrome.webNavigation.onCommitted.addListener(async (details) => {
if (details.frameId !== 0) { // This is an iframe
await injectScripts(details.tabId, [details.frameId], false);
}
}, { url: [{ urlMatches: 'https://*/*' }] });
// Function to handle tab events
async function tabsEventHandler() {
chrome.tabs.query({ currentWindow: true, active: true }, async (tabs) => {
const tabUrl = tabs[0]?.url;
const tabId = tabs[0]?.id;
if (tabUrl && supportedDomains.some((url) => tabUrl.startsWith(url))) {
await injectScripts(tabId, null, true);
getCurrentStateFromStorageAndUpdateBadge();
}
});
}
// Listen for tab updates
chrome.tabs.onUpdated.addListener(async () => { await tabsEventHandler(); });
// Listen for tab switching
chrome.tabs.onActivated.addListener(async () => { await tabsEventHandler(); });
// Listen for extension installation
chrome.runtime.onInstalled.addListener(async () => { await tabsEventHandler(); });
// Listen for changes to the extension state that is persisted in storage
chrome.storage.onChanged.addListener(async () => { getCurrentStateFromStorageAndUpdateBadge(); });