-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
75 lines (63 loc) · 2.43 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
console.log("Content script has loaded via Manifest V3.");
const protectStyleElementContent = (protectStyleEl) => {
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (!MutationObserver) {
return;
}
/* observer, which observe protectStyleEl inner changes, without deleting styleEl */
const innerObserver = new MutationObserver(((mutations) => {
for (let i = 0; i < mutations.length; i += 1) {
const m = mutations[i];
if (protectStyleEl.hasAttribute('mod') && protectStyleEl.getAttribute('mod') === 'inner') {
protectStyleEl.removeAttribute('mod');
break;
}
protectStyleEl.setAttribute('mod', 'inner');
let isProtectStyleElModified = false;
/**
* further, there are two mutually exclusive situations: either there were changes
* the text of protectStyleEl, either there was removes a whole child "text"
* element of protectStyleEl we'll process both of them
*/
if (m.removedNodes.length > 0) {
for (let j = 0; j < m.removedNodes.length; j += 1) {
isProtectStyleElModified = true;
protectStyleEl.appendChild(m.removedNodes[j]);
}
} else if (m.oldValue) {
isProtectStyleElModified = true;
protectStyleEl.textContent = m.oldValue;
}
if (!isProtectStyleElModified) {
protectStyleEl.removeAttribute('mod');
}
}
}));
innerObserver.observe(protectStyleEl, {
'childList': true,
'characterData': true,
'subtree': true,
'characterDataOldValue': true,
});
};
const setStyleContent = (styleEl, cssContent) => {
styleEl.textContent = cssContent;
};
const applyCss = (css) => {
if (!css || css.length === 0) {
return;
}
css.forEach((cssContent) => {
const styleEl = document.createElement('style');
styleEl.setAttribute('type', 'text/css');
setStyleContent(styleEl, cssContent);
(document.head || document.documentElement).appendChild(styleEl);
protectStyleElementContent(styleEl);
})
};
const tryLoadCssAndScripts = async () => {
chrome.runtime.sendMessage({type: 'getCss'}, (response) => {
applyCss(response);
});
};
tryLoadCssAndScripts();