-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
69 lines (65 loc) · 2.05 KB
/
background.js
File metadata and controls
69 lines (65 loc) · 2.05 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
const defaultBlockedWebsites = [
"*://adsense.google.com/start/*",
"*://*googleadservices.com/*",
"*://.doubleclick.net/*",
"*://partner.googleadservices.com/*",
"*://.googlesyndication.com/*",
"*://.google-analytics.com/*",
"*://creative.ak.fbcdn.net/*",
"*://.adbrite.com/*",
"*://.exponential.com/*",
"*://.quantserve.com/*",
"*://.scorecardresearch.com/*",
"*://.zedo.com/*",
"*://.googletagmanager.com/*",
"*://.px.ads.linkedin.com/*",
"*://.twitter.com/*",
];
chrome.runtime.onInstalled.addListener(function () {
// Load the list from Chrome storage
chrome.storage.local.get("blockedWebsites", function (data) {
try {
let blockedWebsites = JSON.parse(data.blockedWebsites);
console.log(blockedWebsites);
formatAndBlockWebsites(blockedWebsites);
} catch (error) {
// if first time visit then block default websites
blockedWebsites = defaultBlockedWebsites;
chrome.storage.local.set(
{ blockedWebsites: JSON.stringify(defaultBlockedWebsites) },
() => {
console.log("default websites stored in localstorage.");
}
);
formatAndBlockWebsites(blockedWebsites);
}
});
});
// Listener for reloading the extension
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.action === "reloadExtension") {
chrome.runtime.reload();
}
});
async function formatAndBlockWebsites(blockedWebsites) {
// Format the list into the required JSON format for declarativeNetRequest
const formattedRules = blockedWebsites.map((website, index) => ({
id: index + 1,
priority: 1,
action: {
type: "block",
},
condition: {
urlFilter: website,
},
}));
console.log(formattedRules);
let oldRules = await chrome.declarativeNetRequest.getDynamicRules();
const oldRuleIds = oldRules.map((rule) => rule.id);
console.log("oldRules", oldRules);
// Set up the rules for blocking websites
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: oldRuleIds,
addRules: formattedRules,
});
}