简体   繁体   中英

How to replace iframe document with another pre-existing document object, without using write()

I just want to replace a blank iframe's document with a pre-existing document object. Not a string of HTML that can use the write() method with (that solution is in many other answers, here) . I just want a document object to replace another document.


My blank iframe:

<iframe src="about:blank" id="myIframe"></iframe>


Routine to replace blank iframe document:

function replaceIframeDoc(objDoc){
    var nod_if    = document.getElementById("myIframe");
    var nod_ifDoc = nod_if.contentWindow.document || nod_if.contentDocument;
    nod_ifDoc     = objDoc;
}


Document object created, and call to do the replace:
(Note: I encapsulate my document object in a simple object... I need to do that for some other unrelated stuff... just to easily transfer some attributes, etc. Hopefully it's inconsequential to my issue!)

var obj_container = new Object;  //just to make easier to do some other stuff
obj_container.document = document.implementation.createHTMLDocument();
obj_container.document.open();
obj_container.document.write("<html>...(some html)...</html>");
obj_container.document.close();
replaceIframeDoc(obj_container.document);

Depending on which browser you need to support, you could do something like this:

var iframe = document.getElementById("myIframe");;
var oldNode = iframe.contentDocument.getElementById("myNode");
var newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);

You can read more here: https://developer.mozilla.org/en-US/docs/Web/API/document.importNode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM