feat(content): remove caching and improve performance

This commit is contained in:
wanhose 2021-04-03 17:09:24 +02:00
parent b406e9604e
commit 9c9752de4b

View File

@ -1,12 +1,11 @@
let attempts = 0; let elements = [];
let filters = [];
const fix = () => { const fix = () => {
const body = document.body.style; const html = document.documentElement;
const html = document.documentElement.style; const body = document.body;
body.setProperty("overflow-y", "unset", "important"); html.style.setProperty("overflow-y", "unset", "important");
html.setProperty("overflow-y", "unset", "important"); body.style.setProperty("overflow-y", "unset", "important");
}; };
const retrieveElement = (match) => { const retrieveElement = (match) => {
@ -32,68 +31,33 @@ const observe = () => {
}); });
}; };
const updateCache = (value) => { const remove = () => {
chrome.storage.local.get([document.location.hostname], (store) => { for (let i = elements.length; i--; ) {
const matches = store[document.location.hostname]; const match = elements[i];
const element = retrieveElement(match);
const tagName = element ? element.tagName.toUpperCase() : "";
chrome.storage.local.set({ if (element && !["BODY", "HTML"].includes(tagName)) {
[document.location.hostname]: matches element.remove();
? [...new Set([...matches, value])]
: [value],
});
});
};
const removeFromCache = () => {
chrome.storage.local.get([document.location.hostname], (value) => {
const matches = value[document.location.hostname];
if (matches && !!matches.length) {
for (let i = matches.length; i--; ) {
const element = retrieveElement(matches[i]);
const tagName = element ? element.tagName.toUpperCase() : "";
if (element && !["BODY", "HTML"].includes(tagName)) {
element.remove();
}
}
}
});
};
const removeFromFilters = () => {
if (attempts < 5) {
for (let i = filters.length; i--; ) {
const match = filters[i];
const element = retrieveElement(match);
const tagName = element ? element.tagName.toUpperCase() : "";
if (element && !["BODY", "HTML"].includes(tagName)) {
element.innerHTML = "";
updateCache(match);
}
} }
} }
}; };
const observer = new MutationObserver((mutations, observer) => { const observer = new MutationObserver((_, instance) => {
mutations.forEach(() => { instance.disconnect();
observer.disconnect(); fix();
fix(); remove();
removeFromCache(); observe();
removeFromFilters();
attempts += 1;
observe();
});
}); });
(async () => { (async () => {
const url = chrome.runtime.getURL("filters/index.txt"); const url = chrome.runtime.getURL("elements/index.txt");
const db = await fetch(url).then((res) => res.text()); const db = await fetch(url).then((res) => res.text());
filters = db.split("\n"); elements = db.split("\n");
fix(); document.addEventListener("DOMContentLoaded", () => {
removeFromCache(); fix();
removeFromFilters(); remove();
observe(); observe();
});
})(); })();