/
background.js
69 lines (61 loc) · 1.96 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
66
67
68
69
const rules = {
"m": {
redirectUrl: "https://mail.google.com",
redirectRegexUrl: "https://mail.google.com/mail/u/0/#search/$1",
matchRegex: "(.*)",
},
"c": {
redirectUrl: "https://calendar.google.com",
redirectRegexUrl: "https://calendar.google.com/calendar/r/search?q=$1",
matchRegex: "(.*)",
},
"g": {
redirectUrl: "https://github.com",
redirectRegexUrl: "https://github.com/$1",
matchRegex: "(.*)",
},
"t": {
redirectUrl: "https://twitter.com",
redirectRegexUrl: "https://twitter.com/$1",
matchRegex: "(.*)",
},
"hn": {
redirectUrl: "https://news.ycombinator.com",
redirectRegexUrl: "https://hn.algolia.com/?query=$1&sort=byPopularity&prefix&page=0&dateRange=all&type=story",
matchRegex: "(.*)",
},
};
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
const url = new URL(details.url);
// move to static default before function
let sr = null;
if (syncedRule == null)
sr = rules;
else
sr = syncedRule;
const target = sr[url.host];
if (target != null) {
let redirectingURL = target.redirectUrl;
if (url.pathname !== "/" && target.matchRegex !== "") {
redirectingURL = url.pathname.substr(1).replace(new RegExp(target.matchRegex), target.redirectRegexUrl);
}
return {
redirectUrl: redirectingURL,
};
}
return {};
},
{urls: ["<all_urls>"]},
["blocking"],
);
chrome.runtime.onInstalled.addListener(function () {
chrome.storage.local.get('rules', ({rules: loadedRules}) => {
if (loadedRules == null) chrome.storage.local.set({rules: rules});
});
});
chrome.storage.local.get('rules', ({rules: loadedRules}) => {
console.log("loaded rules");
console.log(loadedRules);
syncedRule = loadedRules;
});