-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
168 lines (151 loc) · 4.76 KB
/
Copy pathbackground.js
File metadata and controls
168 lines (151 loc) · 4.76 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const RULES_KEY = "rules";
const ENABLED_KEY = "enabled";
function cleanDomain(str) {
return str.trim().replace(/^https?:\/\//i, "").replace(/\/$/, "").replace(/^www\./i, "").toLowerCase();
}
let cachedRules = [];
let cachedEnabled = true;
let isCacheInitialized = false;
async function getState() {
if (!isCacheInitialized) {
const data = await chrome.storage.sync.get([RULES_KEY, ENABLED_KEY]);
cachedRules = Array.isArray(data[RULES_KEY]) ? data[RULES_KEY] : [];
cachedEnabled = data[ENABLED_KEY] !== false;
isCacheInitialized = true;
}
return {
rules: cachedRules,
enabled: cachedEnabled
};
}
async function rebuildRules() {
const { rules, enabled } = await getState();
const existing = await chrome.declarativeNetRequest.getDynamicRules();
const removeRuleIds = existing.map((r) => r.id);
const addRules = [];
if (enabled) {
rules.forEach((rule, index) => {
if (!rule || !rule.from || !rule.to || rule.enabled === false) return;
if (rule.isRegex) {
addRules.push({
id: index + 1,
priority: 1,
action: {
type: "redirect",
redirect: {
regexSubstitution: rule.to
}
},
condition: {
regexFilter: rule.from,
resourceTypes: ["main_frame", "sub_frame"]
}
});
} else {
const cleanFrom = cleanDomain(rule.from);
const cleanTo = cleanDomain(rule.to);
if (!cleanFrom || !cleanTo) return;
addRules.push({
id: index + 1,
priority: 1,
action: {
type: "redirect",
redirect: {
transform: {
host: cleanTo
}
}
},
condition: {
urlFilter: `||${cleanFrom}^`,
resourceTypes: ["main_frame", "sub_frame"]
}
});
}
});
}
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds,
addRules
});
}
chrome.runtime.onInstalled.addListener(rebuildRules);
chrome.runtime.onStartup.addListener(rebuildRules);
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "sync" && (changes[RULES_KEY] || changes[ENABLED_KEY])) {
if (changes[RULES_KEY]) {
cachedRules = Array.isArray(changes[RULES_KEY].newValue) ? changes[RULES_KEY].newValue : [];
// New rule objects — clear any compiled regex from previous cache
}
if (changes[ENABLED_KEY]) {
cachedEnabled = changes[ENABLED_KEY].newValue !== false;
}
isCacheInitialized = true;
rebuildRules();
}
});
function isRuleMatch(url, rule) {
if (!rule.from || !rule.to || rule.enabled === false) return false;
if (rule.isRegex) {
// Use cached compiled regex if available, otherwise compile and cache
if (!rule._regex) {
try {
rule._regex = new RegExp(rule.from);
} catch (e) {
return false;
}
}
return rule._regex.test(url);
} else {
try {
const urlObj = new URL(url);
const host = urlObj.hostname.replace(/^www\./i, "").toLowerCase();
const fromHost = cleanDomain(rule.from);
return host === fromHost || host === `www.${fromHost}`;
} catch (e) {
return false;
}
}
}
const MAX_PENDING = 50;
const pendingNotifications = new Map();
function prunePendingNotifications() {
const cutoff = Date.now() - 15000;
for (const [tabId, item] of pendingNotifications) {
if (item.time < cutoff) pendingNotifications.delete(tabId);
}
// Hard cap: evict oldest if still over limit
if (pendingNotifications.size > MAX_PENDING) {
const oldest = [...pendingNotifications.entries()].sort((a, b) => a[1].time - b[1].time);
oldest.slice(0, pendingNotifications.size - MAX_PENDING).forEach(([id]) => pendingNotifications.delete(id));
}
}
chrome.webRequest.onBeforeRedirect.addListener(
async (details) => {
if (details.tabId >= 0 && details.type === "main_frame") {
const { rules, enabled } = await getState();
if (!enabled) return;
const matched = rules.find((r) => isRuleMatch(details.url, r));
if (matched) {
prunePendingNotifications();
pendingNotifications.set(details.tabId, { rule: matched, time: Date.now() });
}
}
},
{ urls: ["<all_urls>"] }
);
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "CHECK_REDIRECT") {
const tabId = sender.tab && sender.tab.id;
if (tabId && pendingNotifications.has(tabId)) {
const item = pendingNotifications.get(tabId);
pendingNotifications.delete(tabId);
if (Date.now() - item.time < 10000) {
sendResponse({ redirected: true, rule: item.rule });
return true;
}
}
sendResponse({ redirected: false });
}
return true;
});