Find and replace a string

Is it possible to look at the source code of a page, find a specific part and replace it with something else before the page loads? I would like to accomplish this using JavaScript in order to use it in a Chrome extension. So something like this:

Find google.com

<script type="text/javascript"> var URLgo = "http://google.com"; </script> 

Replace with yahoo.com

 <script type="text/javascript"> var URLgo = "http://yahoo.com"; </script> 
+6
source share
1 answer
 <script type="text/javascript"> function replaceScript() { var toReplace = 'http://google.com'; var replaceWith ='http://yahoo.com'; document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith); } </script> 

Then initialize the body tag to load the page.

 <body onload="replaceScript();"> 

It should work fine and replace all instances in the html body code.

If it is in an iframe with the identifier "external_iframe", you should change document.body.innerHTML as:

 window.frames['external_iframe'].document.body.innerHTML 

Although I'm not sure that you can use it for an external site.

There seems to be some info here: Javascript Iframe innerHTML

+3
source

Source: https://habr.com/ru/post/887728/


All Articles