I used this piece of code, to replace text strings in my webpage:
function walkText(node) {
if (node.nodeType == 3) {
node.data = node.data.replace(/Villa/g, "Replaced");
node.data = node.data.replace(/Apartment/g, "Replaced2");
}
if (node.nodeType == 1 && node.nodeName != "SCRIPT") {
for (var i = 0; i < node.childNodes.length; i++) {
walkText(node.childNodes[i]);
}
}
}
walkText(document.body);
Villa
Apartment
This works fine on static content, but will not work on content that gets loaded dynamically through ajax. Is there a workaround to make this work on text that is not static/not loaded on page load?
Thanks.
2
Answers
A basic, simple way to do this is to observe your page with
MutationObserver
. Below I have created a very simple example for this:The only modifications I had to make is to ensure that the text only updates when necessary, to prevent triggering an infinite loop. Otherwise, with this, it seems pretty efficient.
Docs: MutationObserver (MDN)
Use
MutationObserver
for added nodes and replace the text:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Don’t forget to disconnect the observer when you replace text otherwise you will react on own mutations and could go into an infinite loop.