How to copy iframe content to div?

2019-07-15 04:27发布

问题:

See code snippet below. I want the output text in the iframe to show in the #source div. I’m struggeling with this, and am grateful for any ideas. How can I copy the output text in the iframe to a div? (The script writes "Can see text!" in div #show if div #sourcediv contains "Text", else "Cannot see text!".)

<html>
<body>

<div id="source"></div>
<div id="show"></div> 

<script> 
if (document.getElementById('source').innerHTML.indexOf("Text") != -1)
{document.getElementById('show').innerHTML="Can see text!";}
else{document.getElementById('show').innerHTML="Cannot see text!";}
</script>

<iframe id="iframe" src="http://majaulrika.esy.es/text.txt">

</body>
</html>

回答1:

Keeping in mind that your iframe is on the same domain as your page:

// Get your iframe element

var iframe = document.getElementById('iframe');

// Access contents of it like this

var iframeContent = iframe.contentWindow.document;

// Get your div element

var content = document.getElementById('source');

// set contents of this div to iframe's content

content.innerHTML = iframeContent.innerHTML;

Depending on when you're doing this, it also might be worth to wait till the iframe loads:

iframe.onload = function() { /* put the above code here */ }


回答2:

Further your comment:

A better solution to get a content from file is to use ajax.

Here is a simple approach of using ajax with jQuery.

$.ajax({
  url: 'http://output.jsbin.com/sebusu',
  success: function(data) {
    $('#source').html(data);
    $('#show').text(function(){
      if (data.indexOf('Text') != -1) {
        return 'Can see text!';
      }
      else {
        return "Can't see text!";
      }
    });
  },
  error: function(){
    console.log(error);
  }
});
<div id="source"></div>
<div id="show"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Live Demo

Again, you can call ajax only for your website (with some exceptions)