-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbackground.js
78 lines (70 loc) · 2.04 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
70
71
72
73
74
75
76
77
78
let DEFAULT_LIST_URL =
"https://cdn.jsdelivr.net/gh/nileshtrivedi/better/defaultlist.json";
var BETTER_ALTERNATIVES = [];
chrome.runtime.onInstalled.addListener(function () {
console.log("onInstalled....");
onStartup();
});
// fetch and save data when chrome restarted
chrome.runtime.onStartup.addListener(() => {
console.log("onStartup....");
onStartup();
});
function fetchAllLists(listUrls) {
var promises = listUrls.map(
(listUrl) => fetch(listUrl).then((resp) => resp.json())
// .catch((e) => console.log("List errored out", e))
);
// wait for all requests to complete, ignore errors
Promise.all(promises.map((p) => p.catch((e) => null))).then((results) => {
BETTER_ALTERNATIVES = results.filter((item) => item != null);
chrome.storage.local.set({ betterSourceData: results }, function () {
console.log("Set betterSource");
});
});
}
function onStartup() {
chrome.storage.sync.get(["betterSourceUrls"], function (result) {
let betterSourceUrls = [];
if (result && result.betterSourceUrls) {
betterSourceUrls = JSON.parse(result.betterSourceUrls);
}
if (betterSourceUrls.length === 0) {
betterSourceUrls = [DEFAULT_LIST_URL];
}
fetchAllLists(betterSourceUrls);
});
}
function getMatch(url) {
var matches = BETTER_ALTERNATIVES.reduce((result, sourceList) => {
var match = sourceList.find((pattern) =>
url.match(new RegExp(pattern.urlPattern))
);
if (match && match.alternatives) result.push(match);
return result;
}, []);
if (matches.length) {
var combinedMatch = {
urlPattern: matches[0].urlPattern,
alternatives: matches.reduce(
(result, match) => result.concat(match.alternatives),
[]
),
};
return combinedMatch;
}
return null;
}
chrome.runtime.onMessage.addListener((msg, sender, response) => {
switch (msg.type) {
case "getMatch":
response(getMatch(msg.url));
break;
case "reloadList":
onStartup();
break;
default:
response("unknown request");
break;
}
});