Creating my debut Chrome extension, I'm developing a tool to substitute text on web pages.
The current code effectively operates on content loaded by DOMContentLoaded. However, when pages employ infinite scrolling and new content is added, the text replacement process fails.
I am seeking a solution that will automatically execute text replacement on any dynamically added content.
Prior attempts with an 'onscroll' event listener proved to be cumbersome and resource-intensive. Surely, there must be a more efficient approach.
Although I explored using the manifest's run_at property, I have not yet discovered a method to apply it in this context.
let elements = document.getElementsByTagName('*');
let replacements = {
"first to replace": "new text",
"second to replace": "also new text"
};
let keys = Object.keys(replacements);
RegExp.quote = (str) => {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
let makeItAwesomer = () => {
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
for (var j = 0; j < element.childNodes.length; j++) {
let node = element.childNodes[j];
if (node.nodeType === 3) {
let text = node.nodeValue;
let newText = text;
if(keys.some(function(key){
return ~text.toLowerCase().indexOf(key.toLowerCase());
})) {
keys.forEach( key => {
let regex = new RegExp(RegExp.quote(key), "gi");
newText = newText.replace(regex, replacements[key]);
});
if (newText != text) {
element.replaceChild(document.createTextNode(newText), node);
}
}
}
}
}
}
makeItAwesomer();