-
Notifications
You must be signed in to change notification settings - Fork 3
/
background.js
65 lines (57 loc) · 2.28 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
const redirectList = [
{ id: 1, label: "google -> startpage", from: "https://www.google.com(.*)", to: "https://www.startpage.com\\1", enabled: false },
{ id: 2, label: "youtube -> piped", from: "(.*)youtube.com(.*)", to: "https://piped.kavin.rocks\\2", enabled: true },
{ id: 3, label: "reddit -> libreddit", from: "(.*)reddit.com(.*)", to: "https://libredd.it\\2", enabled: true },
]
let localRedirectList
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({ hardRedirectorList: redirectList })
chrome.storage.local.get("hardRedirectorList", (localRedirectList) => {
clearSessionRules(redirectList)
applySessionRules(localRedirectList)
});
});
chrome.runtime.onStartup.addListener(() => {
chrome.storage.local.get("hardRedirectorList", (localRedirectList) => {
clearSessionRules(redirectList)
applySessionRules(localRedirectList)
});
})
chrome.storage.onChanged.addListener(function (changes, namespace) {
if (namespace === "local" && changes.hardRedirectorList?.newValue) {
chrome.storage.local.get("hardRedirectorList", (localRedirectList) => {
clearSessionRules(redirectList)
applySessionRules(localRedirectList)
});
}
});
let clearSessionRules = (redirectList) => {
chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: Array(redirectList.length).fill().map((_, i) => i + 1)
})
}
let applySessionRules = (localRedirectList) => {
chrome.declarativeNetRequest.updateSessionRules(formatRules(onlyEnabled(localRedirectList.hardRedirectorList)))
}
let onlyEnabled = (localRedirectList) => {
return localRedirectList.filter((rule) => { return rule.enabled == true })
}
let formatRules = (localRedirectList) => {
let delIds = []
let rules = []
for (let i = 0; i < localRedirectList.length; i++) {
rules.push({
id: localRedirectList[i].id,
action: {
type: "redirect",
redirect: { regexSubstitution: localRedirectList[i].to }
},
condition: {
resourceTypes: ["main_frame"],
regexFilter: localRedirectList[i].from
}
})
delIds.push(i + 1)
}
return { removeRuleIds: delIds, addRules: rules }
}