最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Copy innerHTML of an iframe within another iframe - Stack Overflow

programmeradmin2浏览0评论

I stumbled a website like this, let's call it home.html

<body>
<iframe id='id1' src="1.html">
</iframe>
</body>

In 1.html, we got

<body>...
<iframe id='id2' src="2.html">
</iframe>
...
</body>

How can I get the HTML content of 2.html with JavaScript? The reason I do not go directly to 2.html to get the content is because the content is simply a template and get changed dynamically at the home.html

Usually, i would just do like below to get the content of an iframe id but it doesn't work in this case.

var e = document.getElementById('myid').html;

Thank you.

I stumbled a website like this, let's call it home.html

<body>
<iframe id='id1' src="1.html">
</iframe>
</body>

In 1.html, we got

<body>...
<iframe id='id2' src="2.html">
</iframe>
...
</body>

How can I get the HTML content of 2.html with JavaScript? The reason I do not go directly to 2.html to get the content is because the content is simply a template and get changed dynamically at the home.html

Usually, i would just do like below to get the content of an iframe id but it doesn't work in this case.

var e = document.getElementById('myid').html;

Thank you.

Share Improve this question edited Jun 27, 2013 at 7:38 thSoft 22.7k6 gold badges95 silver badges105 bronze badges asked Jun 27, 2013 at 7:10 Tuan Anh TranTuan Anh Tran 1393 silver badges9 bronze badges 2
  • 3 Are all of these iframes on the same domain? – Matthew Graves Commented Jun 27, 2013 at 7:12
  • Tried document.frames[0].frames[0].getElementById('myid')? – Sven Schneider Commented Jun 27, 2013 at 7:12
Add a ment  | 

4 Answers 4

Reset to default 5

Try this,

var iFrame =  document.getElementById('id1');
var iFrameBody= iframe.contentDocument || iframe.contentWindow.document;
content= iFrameBody.getElementsByTagName('body')[0].innerHTML;
alert(content);

your iframes src should be same to your main page domain. Different domain content access is blocked by browsers. Same domain iframe contents can be accessed.

It is not enough to copy just BODY tag content between iframes, but you need to copy HEAD tag content as well to get the same design of new iframe

var iFrameDocument= iframe.contentDocument || iframe.contentWindow.document;
alert(iFrameDocument.head.innerHTML);
alert(iFrameDocument.body.innerHTML);

If you want to copy the body with his properties you can now do :

iframe1.contentWindow.document.body = iframe2.contentWindow.document.body.cloneNode(true);

cloneNode(true) will copy every child of the specified node

发布评论

评论列表(0)

  1. 暂无评论