-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
92 lines (80 loc) · 2.56 KB
/
content.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
navigator.storage.persist();
function applyFilter(node) {
if (node.style)
node.style.filter =
"invert(100%) hue-rotate(180deg) contrast(80%) saturate(80%)";
}
function removeFilter(node) {
if (node.style) node.style.filter = "none";
}
function searchIFrames(doc) {
let imgList = [];
doc.querySelectorAll("iframe").forEach((iframe) => {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
imgList = imgList.concat(searchImages(iframeDoc) || []);
imgList = imgList.concat(searchBackgroundImages(iframeDoc) || []);
imgList = imgList.concat(searchVideo(iframeDoc) || []);
imgList = imgList.concat(searchIframes(iframeDoc) || []);
} catch (e) {
// no-op
}
});
return imgList;
}
function searchImages(doc) {
return Array.from(doc.images);
}
function searchBackgroundImages(doc) {
const srcChecker = /url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/i;
return Array.from(
Array.from(doc.querySelectorAll("*")).reduce((collection, node) => {
let prop = window
.getComputedStyle(node, null)
.getPropertyValue("background-image");
let match = srcChecker.exec(prop);
if (match) {
collection.add(match[1]);
}
return collection;
}, new Set())
);
}
function searchVideo(doc) {
return Array.from(doc.querySelectorAll("video"));
}
function darkenPage() {
applyFilter(window.document.querySelector("html"));
searchImages(window.document).forEach(applyFilter);
searchBackgroundImages(window.document).forEach(applyFilter);
searchIFrames(window.document).forEach(applyFilter);
searchVideo(window.document).forEach(applyFilter);
window.document.body.classList.add("darkviewer-active");
}
function undarkenPage() {
removeFilter(window.document.querySelector("html"));
searchImages(window.document).forEach(removeFilter);
searchBackgroundImages(window.document).forEach(removeFilter);
searchIFrames(window.document).forEach(removeFilter);
searchVideo(window.document).forEach(removeFilter);
window.document.body.classList.remove("darkviewer-active");
}
function addStyle() {
const style = document.createElement("style");
style.textContent = `
.darkviewer-active {
background: #fff;
color: #000;
}
`;
document.head.appendChild(style);
}
const url = new URL(window.location.href);
const hostname = url.hostname;
chrome.storage.sync.get([hostname]).then((obj) => {
if (obj[hostname]) {
chrome.runtime.sendMessage({ action: "darken" });
} else {
chrome.runtime.sendMessage({ action: "undarken" });
}
});