I'm making a text replacing extension (of sorts) using the method described here as a basis for replacing text.
Here is the important piece of code
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
for (var j = 0; j < element.childNodes.length; j++) {
var node = element.childNodes[j];
if (node.nodeType === 3) {
var text = node.nodeValue;
var replacedText = text.replace(/[word or phrase to replace here]/gi, '[new word or phrase]');
if (replacedText !== text) {
element.replaceChild(document.createTextNode(replacedText), node);
}
}
}
}
Now this works fine in 99% of cases, but on some computers (I'm assuming based on the speed of the computer and what it has cached) this code will not work on certain websites, most importantly on google searches. The script definitely runs, but it doesn't find anything to replace. My best guess is that it is loading and running the script before it finishes loading and adding all the data from google onto the DOM.
I have two questions
1) Is there any way to detect that google has finished doing what it needs to do before running the script? Or is this inherently impossible because (I assume) there is some asynchronous stuff happening.
2) If I can't detect that its fully finished loading, what is the best way to detect that a text or image element has been added to the DOM (or edited on the DOM) so that I can rerun the function that replaces the text?
Thanks in advance for the help.