metamorpov/content_script.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-10-19 05:27:27 -04:00
DEACTIVATE_KEY = 'deactivate-this-extension-pls-interactive-fics-yalla-bina';
2017-05-19 12:13:06 -04:00
2019-10-19 05:27:27 -04:00
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
escapeAndReplace(message.input_word, message.replace_value)
});
const replaceAll = () => {
chrome.storage.local.get(null, items => {
if (!items[DEACTIVATE_KEY]) {
2019-10-19 06:24:14 -04:00
for (var key in items) {
2019-10-19 05:27:27 -04:00
if (key == 'person') {
const regexp_y_n = /\by\/n\b|\(y\/n\)|\[y\/n\]/ig
replace(regexp_y_n, items[key])
} else if (key !== DEACTIVATE_KEY) {
escapeAndReplace(key, items[key])
2016-07-06 01:12:36 -04:00
}
2016-06-18 23:04:38 -04:00
}
}
2019-10-19 05:27:27 -04:00
})
2016-07-06 01:12:36 -04:00
}
2016-06-18 23:04:38 -04:00
2019-10-19 05:27:27 -04:00
const escapeAndReplace = (input_word, replace_value) => {
2019-10-19 06:24:14 -04:00
const input_word_escaped = escapeRegExp(input_word.trim())
const regexp_input_word = new RegExp(`\\b${input_word_escaped}\\b`, "ig")
2019-10-19 05:27:27 -04:00
replace(regexp_input_word, replace_value)
2016-06-18 23:04:38 -04:00
}
2019-10-19 05:27:27 -04:00
const escapeRegExp = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
2015-02-21 22:00:28 -05:00
2019-10-19 05:27:27 -04:00
const replace = (input_word, replace_value) => {
chrome.storage.local.get(DEACTIVATE_KEY, obj => {
if (replace_value && !obj[DEACTIVATE_KEY]) {
walk(document.body, input_word, replace_value)
2017-05-19 12:13:06 -04:00
}
2019-10-19 05:27:27 -04:00
})
}
const replaceText = (textNode, input_word, replace_value) => {
2019-10-19 06:24:14 -04:00
let node_value = textNode.nodeValue
2019-10-19 05:27:27 -04:00
node_value = node_value.replace(input_word, replace_value)
textNode.nodeValue = node_value
2015-02-21 22:00:28 -05:00
}
function walk(node, v, p){
2015-02-21 22:00:28 -05:00
// I stole this function from here:
// http://is.gd/mwZp7E
var child, next;
switch (node.nodeType){
2015-02-21 22:00:28 -05:00
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while (child){
2015-02-21 22:00:28 -05:00
next = child.nextSibling;
walk(child, v, p);
2015-02-21 22:00:28 -05:00
child = next;
}
break;
case 3: // Text node
2019-10-19 05:27:27 -04:00
replaceText(node, v, p);
2015-02-21 22:00:28 -05:00
break;
}
}
2019-10-19 05:27:27 -04:00
replaceAll()