gpt4 book ai didi

javascript - 如何深度克隆iframe?

转载 作者:搜寻专家 更新时间:2023-11-01 04:19:35 25 4
gpt4 key购买 nike

有没有办法深度克隆iframe?

基本的 jQuery 克隆只是制作另一个具有相同 src 的 iframe。我想要实现的是一种克隆 iframe 的方法,它是准确的当前内容(即任何可能的输入值、通过 javascript 进行的任何 DOM 修改等)。

var clone = iframe.contents().find('html').clone();

当我克隆 HTML 属性及其所有子属性、修改等时,我遇到了这些问题:

  1. 我缺少 DOCTYPE

  2. 如何将其插入到新的 iFrame 中?

最佳答案

如果您克隆 iframe 创建另一个 iframe 那么您深度克隆了您的 iframe!它的来源在其他地方,当您分配它的 src 属性时,它会被下载。

测试

假设您有一个打印当前时间的(非缓存)页面作为源。在您的页面上放置一个 iframe,等待 10 秒,然后克隆它。新的 iframe 将下载其内容,第二个 iframe 将具有不同的内容(时间)。

“真正的”深度克隆

编辑:如果您需要深度原始克隆,您可以获取 innerHTML 并将其注入(inject)到 iframe 中。来自 Michael Mahemof 的解决方案:

// Creates the new iframe, add the iframe where you want
var newframe = document.createElement("iframe");
document.body.appendChild(newframe);

// We need the iframe document object, different browsers different ways
var frameDocument = newFrame.document;
if (newFrame.contentDocument)
frameDocument = newFrame.contentDocument;
else if (newFrame.contentWindow)
frameDocument = newFrame.contentWindow.document;

// We open the document of the empty frame and we write desired content.
// originalHtmlContent is a string where you have the source iframe HTML content.
frameDocument.open();
frameDocument.writeln(originalHtmlContent);
frameDocument.close();

关于javascript - 如何深度克隆iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com