-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
60 lines (53 loc) · 1.5 KB
/
content.js
File metadata and controls
60 lines (53 loc) · 1.5 KB
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
// Text replacement pairs
const replacements = [
{ pattern: /microsoft/gi, replacement: 'MicroSlop' },
{ pattern: /elon musk/gi, replacement: 'Felon Mask' }
];
// Function to replace text in a text node
function replaceText(node) {
let text = node.nodeValue;
let modified = false;
replacements.forEach(({ pattern, replacement }) => {
if (pattern.test(text)) {
text = text.replace(pattern, (match) => {
// Preserve original capitalization pattern
if (match === match.toUpperCase()) {
return replacement.toUpperCase();
} else if (match[0] === match[0].toUpperCase()) {
return replacement.charAt(0).toUpperCase() + replacement.slice(1);
}
return replacement.toLowerCase();
});
modified = true;
}
});
if (modified) {
node.nodeValue = text;
}
}
// Walk through all text nodes in the document
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
replaceText(node);
} else {
for (let i = 0; i < node.childNodes.length; i++) {
walk(node.childNodes[i]);
}
}
}
// Initial replacement
walk(document.body);
// Watch for DOM changes and replace text in new nodes
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE) {
walk(node);
}
});
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});