-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
76 lines (64 loc) · 1.93 KB
/
background.js
File metadata and controls
76 lines (64 loc) · 1.93 KB
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
66
67
68
69
70
71
72
73
74
75
76
// background.js
chrome.action.onClicked.addListener(() => {
chrome.runtime.openOptionsPage();
});
chrome.alarms.create("keepAlive", { periodInMinutes: 1 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "keepAlive") {
console.log("Service worker alive");
}
});
async function updateBlockRules() {
// First remove ALL existing rules from previous updates
const existingRules = await chrome.declarativeNetRequest.getDynamicRules();
const existingRuleIds = existingRules.map((rule) => rule.id);
if (existingRuleIds.length > 0) {
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existingRuleIds,
});
}
// Then add new rules based on current blocked sites
const result = await chrome.storage.local.get(["blockedSites"]);
const blockedSites = result.blockedSites || [];
const rules = blockedSites
.map((url, index) => {
let parsedUrl;
try {
parsedUrl = new URL(url.startsWith("http") ? url : `https://${url}`);
} catch (e) {
console.error(`Invalid URL: ${url}`);
return null;
}
let domain = `${parsedUrl.hostname}/*`;
return {
id: index + 1,
priority: 1,
action: { type: "block" },
condition: {
urlFilter: domain,
resourceTypes: [
"main_frame",
"sub_frame",
"script",
"stylesheet",
"image",
"xmlhttprequest",
"other",
],
},
};
})
.filter((rule) => rule !== null); // Filter out any invalid URLs
if (rules.length > 0) {
await chrome.declarativeNetRequest.updateDynamicRules({
addRules: rules,
});
}
}
chrome.storage.onChanged.addListener(function (changes) {
if (changes.blockedSites) {
updateBlockRules();
}
});
chrome.runtime.onStartup.addListener(updateBlockRules);
chrome.runtime.onInstalled.addListener(updateBlockRules);