-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_script.js
More file actions
94 lines (79 loc) · 2.71 KB
/
Copy pathcontent_script.js
File metadata and controls
94 lines (79 loc) · 2.71 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
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
93
94
function walk(rootNode)
{
// Find all the text nodes in rootNode
var walker = document.createTreeWalker(
rootNode,
NodeFilter.SHOW_TEXT,
null,
false
),
node;
// Modify each text node's value
while (node = walker.nextNode()) {
handleText(node);
}
}
function handleText(textNode) {
textNode.nodeValue = replaceText(textNode.nodeValue);
}
function replaceText(v)
{
// Poker needs to change
v = v.replace(/\bPoker\b/g, "Po0ol");
v = v.replace(/\bpoker\b/g, "po0ol");
// Pool needs to change
v = v.replace(/\bPool\b/g, "Poker");
v = v.replace(/\bpool\b/g, "poker");
// Poker needs to change, continued
v = v.replace(/\bPo0ol\b/g, "Pool");
v = v.replace(/\bpo0ol\b/g, "pool");
return v;
}
// Returns true if a node should *not* be altered in any way
function isForbiddenNode(node) {
return node.isContentEditable || // DraftJS and many others
(node.parentNode && node.parentNode.isContentEditable) || // Special case for Gmail
(node.tagName && (node.tagName.toLowerCase() == "textarea" || // Some catch-alls
node.tagName.toLowerCase() == "input"));
}
// The callback used for the document body and title observers
function observerCallback(mutations) {
var i, node;
mutations.forEach(function(mutation) {
for (i = 0; i < mutation.addedNodes.length; i++) {
node = mutation.addedNodes[i];
if (isForbiddenNode(node)) {
// Should never operate on user-editable content
continue;
} else if (node.nodeType === 3) {
// Replace the text for text nodes
handleText(node);
} else {
// Otherwise, find text nodes within the given node and replace text
walk(node);
}
}
});
}
// Walk the doc (document) body, replace the title, and observe the body and title
function walkAndObserve(doc) {
var docTitle = doc.getElementsByTagName('title')[0],
observerConfig = {
characterData: true,
childList: true,
subtree: true
},
bodyObserver, titleObserver;
// Do the initial text replacements in the document body and title
walk(doc.body);
doc.title = replaceText(doc.title);
// Observe the body so that we replace text in any added/modified nodes
bodyObserver = new MutationObserver(observerCallback);
bodyObserver.observe(doc.body, observerConfig);
// Observe the title so we can handle any modifications there
if (docTitle) {
titleObserver = new MutationObserver(observerCallback);
titleObserver.observe(docTitle, observerConfig);
}
}
walkAndObserve(document);