Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find and replace string

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

Find the 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>
like image 608
sarsar Avatar asked May 10 '11 14:05

sarsar


1 Answers

<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 initialise in the body tag to do on page load.

<body onload="replaceScript();">

Should work fine and replace all instances in html body code.

If it is in an iframe with id "external_iframe" then you would modify document.body.innerHTML to be:

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

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

Seems to be some info here: Javascript Iframe innerHTML

like image 108
Pete Hamilton Avatar answered Oct 04 '22 09:10

Pete Hamilton