Replacing text in HTML using JavaScript

I am trying to write a JavaScript program without using jQuery to replace all visible target text on a web page without breaking the functionality of the page.

In particular, I'm trying to make a Chrome extension that does this passively on sites like Facebook.

I experienced limited success with the following:

checkLoad(); function checkLoad(){ if (document.readyState === "complete") { document.body.innerHTML = document.body.innerHTML.replace("target string", "replacement string"); } else { setTimeout('checkLoad();', 500) } } 

This code skips things like names of people, names, etc.

I looked around and can not find a working solution. Any ideas?

+4
source share
2 answers

Simple regex to fix it:

 document.body.innerHTML = document.body.innerHTML.replace(/target string/g, "replacement string"); 
+2
source

I would recommend not replacing innerHTML for several reasons from this blog ( https://j11y.io/javascript/replacing-text-in-the-dom-solved/ ):

  • You cannot guarantee the replacement of text by text. Maybe this is an attribute in html or other appropriate code.
  • Dumps the document and, in my case, again released my chrome extension. This led to my reboot again and again.

I solved this by downloading the js file from the blog and calling it like this:

  var regex = new RegExp(targetString, "g"); findAndReplaceDOMText(document.body, { find: regex, replace: function(portion) { var e = document.createElement('span'); e.appendChild(document.createTextNode(replacementString)); return e; } }); 

My use case wraps the text replaced in the span tag, so it is slightly different from yours. This javascript function is very flexible.

0
source

All Articles