-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreplace.js
More file actions
47 lines (42 loc) · 1.07 KB
/
replace.js
File metadata and controls
47 lines (42 loc) · 1.07 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
(function() {
var rules;
function walk(node) {
// I stole this function from here:
// http://is.gd/mwZp7E
var child, next;
switch ( node.nodeType )
{
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while (child)
{
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
node.nodeValue = handleText(node.nodeValue);
break;
}
}
function handleText(text) {
// Run replacement rules
for (var from in rules) {
var to = rules[from],
pattern = new RegExp('\\b' + from + '\\b'),
matches = text.match(pattern);
if (matches && isStringValidFunction(to)) {
to = evalStringReplaceFunction(to, matches);
}
text = text.replace(new RegExp('\\b' + from + '\\b', 'ig'), to);
}
return text;
}
chrome.storage.local.get('rules', function(response) {
rules = response.rules;
walk(document.body);
});
})();