6

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>
revelt
  • 2,312
  • 1
  • 25
  • 37
sarsar
  • 1,431
  • 4
  • 14
  • 17

1 Answers1

4
<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

Community
  • 1
  • 1
Pete Hamilton
  • 7,730
  • 6
  • 33
  • 58
  • because I plan on loading a page with an iframe. – sarsar May 10 '11 at 14:47
  • The issue is not with the JS. It appears that SBTV have disabled the use of their site in iframes. My answer should work fine, it's the external site which is preventing you viewing content. – Pete Hamilton May 11 '11 at 23:20