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

javascript - How to deep clone iframe? - Stack Overflow

programmeradmin1浏览0评论

Is there any way to deep clone iframe?

Basic jQuery cloning just makes another iframe with the same src. What I want to achieve is a way to clone the iframe and it's exact current content (ie. any possible input values, any DOM modifications through javascript etc.).

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

When i clone the HTML attribute and all its children's, modifications etc I have these problems:

  1. I'm missing the DOCTYPE

  2. how do I insert it into the new iFrame?

Is there any way to deep clone iframe?

Basic jQuery cloning just makes another iframe with the same src. What I want to achieve is a way to clone the iframe and it's exact current content (ie. any possible input values, any DOM modifications through javascript etc.).

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

When i clone the HTML attribute and all its children's, modifications etc I have these problems:

  1. I'm missing the DOCTYPE

  2. how do I insert it into the new iFrame?

Share Improve this question edited Mar 14, 2012 at 13:11 Andreas Louv 47.1k13 gold badges107 silver badges126 bronze badges asked Mar 14, 2012 at 12:56 crappishcrappish 2,7084 gold badges29 silver badges42 bronze badges 1
  • Missing the DOCTYPE shouldn't matter, AFAIK: it's a signal to the parser. Since you already have DOM elements, they shouldn't need to be parsed. – lonesomeday Commented Mar 14, 2012 at 13:15
Add a ment  | 

1 Answer 1

Reset to default 4

If you clone the iframe creating another iframe then you deep clone your iframe! It's source is somewhere else and it'll be downloaded when you assign its src attribute.

Test

Imagine you have as source a (non cached) page that prints the current time. Put an iframe on your page, wait 10 seconds then clone it. The new iframe will download its content and the 2nd iframe will have a different content (the time).

"Real" deep cloning

EDIT: if you need a deep raw clone you may get the innerHTML and inject it inside the iframe. Solution from 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();
发布评论

评论列表(0)

  1. 暂无评论