将一个iframe的innerHTML复制到另一个ifame中

Copy innerHTML of an iframe within another iframe

本文关键字:复制 innerHTML 另一个 ifame iframe 一个      更新时间:2023-09-26

我偶然发现了一个这样的网站,我们称之为home.html

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

1.html中,我们得到了

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

如何使用JavaScript获取2.html的HTML内容?我不直接去2.html获取内容的原因是,内容只是一个模板,在home.html 上会动态更改

通常,我只想在下面获取iframe id的内容,但在这种情况下不起作用。

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

谢谢。

试试这个,

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

您的iframes-src应该与主页域相同。不同的域内容访问被浏览器阻止。可以访问相同的域iframe内容。

在iframe之间仅复制BODY标记内容是不够的,但还需要复制HEAD标记内容才能获得新iframe 的相同设计

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

如果你想用他的属性复制身体,你现在可以做:

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

cloneNode(true)将复制指定节点的每个子节点