How to copy iframe content to div?

≯℡__Kan透↙ 提交于 2019-12-12 17:21:46

问题


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)



来源:https://stackoverflow.com/questions/40769161/how-to-copy-iframe-content-to-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!