简体   繁体   中英

Changing text inside an iframe with JS

I have an HTML page which loads some content in an iframe with the help of remote JS. I want to replace the text "premium content" with something else.

What I am trying is:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://gaand.comli.com/no.js"></script>

<img src="psss" onerror="myFunction()"></img>
<script>
function myFunction() {
    var x = document.getElementById("overlay_iframe");
    var y = x.contentDocument;
    y.document.body.innerHTML = y.document.body.innerHTML.replace('premium', 

'newtext'); 
}
</script>
</body>
</html>

Is there any way to change it as soon as the page is loaded completely?

You can use jquery to have event when page loads, and then replace html content.

$( document ).ready(function() {
   $( "#overlay_iframe" ).html( $( "#overlay_iframe" ).html().replace("premium","newtext"));
});

Unless the iFrame is on your server you cannot change it. I would suggest using PHP

file_get_contents()

and replacing it within the string.

You can try using the jQuery .contents() to return an object of the iframes contents and than manipulate that. jQuery .contents()

Edit, updated

Try

$.getScript("http://gaand.comli.com/no.js")
.done(function(script) {
    s = setInterval(function() {
      $("iframe").contents()
      .find("body").text(function(_, o) {
         return o.replace("premium", "newText");
      }) && clearInterval(s);
    }, 10);
});

jsfiddle http://jsfiddle.net/guest271314/whjqqtco/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM