migliori-alternative/background.js

78 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

let DEFAULT_LIST_URL =
2020-09-12 13:49:11 +02:00
"https://cdn.jsdelivr.net/gh/nileshtrivedi/better/defaultlist.json";
2020-08-02 19:34:43 +02:00
var BETTER_ALTERNATIVES = [];
2020-09-12 13:49:11 +02:00
chrome.runtime.onInstalled.addListener(function () {
console.log("onInstalled....");
2020-08-02 20:00:38 +02:00
onStartup();
2020-08-02 19:34:43 +02:00
});
2020-08-02 20:00:38 +02:00
// fetch and save data when chrome restarted
2020-08-02 19:34:43 +02:00
chrome.runtime.onStartup.addListener(() => {
2020-09-12 13:49:11 +02:00
console.log("onStartup....");
2020-08-02 19:34:43 +02:00
onStartup();
});
2020-09-12 13:49:11 +02:00
function fetchAllLists(listUrls) {
var promises = listUrls.map(
(listUrl) => fetch(listUrl).then((resp) => resp.json())
// .catch((e) => console.log("List errored out", e))
2020-09-12 13:49:11 +02:00
);
2020-08-02 19:34:43 +02:00
// 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);
2020-09-12 13:49:11 +02:00
chrome.storage.local.set({ betterSourceData: results }, function () {
console.log("Set betterSource");
2020-08-02 19:34:43 +02:00
});
2020-09-12 13:49:11 +02:00
});
2020-08-02 19:34:43 +02:00
}
2020-09-12 13:49:11 +02:00
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);
2020-09-12 13:49:11 +02:00
});
}
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;
2020-08-02 19:34:43 +02:00
}
chrome.runtime.onMessage.addListener((msg, sender, response) => {
switch (msg.type) {
2020-09-12 13:49:11 +02:00
case "getMatch":
response(getMatch(msg.url));
break;
case "reloadList":
onStartup();
break;
default:
response("unknown request");
break;
2020-08-02 19:34:43 +02:00
}
});