find and replace string

15,047
<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

Share:
15,047
sarsar
Author by

sarsar

Updated on June 19, 2022

Comments

  • sarsar
    sarsar almost 2 years

    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>
    
  • sarsar
    sarsar almost 13 years
    because I plan on loading a page with an iframe.
  • Pete Hamilton
    Pete Hamilton almost 13 years
    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.