Wednesday, August 6th, 2008
Introducing HTML into an iframe and getting it back
Michael Mahemof is working a lot with TiddlyWiki and posted on how the project injects HTML into an iframe, and then get them out later. This enables you to use the browser parser to do its thing:
-
-
// put it in
-
var doc = iframe.document;
-
if (iframe.contentDocument)
-
doc = iframe.contentDocument; // For NS6
-
else if(iframe.contentWindow)
-
doc = iframe.contentWindow.document; // For IE5.5 and IE6
-
-
// Put the content in the iframe
-
doc.open();
-
doc.writeln(content);
-
doc.close();
-
-
// and then get it out
-
var storeArea = doc.getElementById("storeArea");
-












This is really old and there is no trick. Just simple and standard DOM.
More than being simple and standard DOM, one wonders why it’s promoting such a weird way of writing content to the frame rather than using standard DOM operations there too.
I think one of the things missing from the above description and the original page is why you would want to use this rather than writing the content to a DIV.
Hmm, that’s a lot of code for doing the same this as this:
”
var container = document.createElement(”DIV”);
container.innerHTML = “foobar”;
var ul = container.firstChild;
“
Hmm, Wordpress takes away the html instead of converting it to htmlchars.
http://pastebin.com/f5e4fc48e
I can think of a few reasons why you would want to render an HTML string into an iframe:
1 - you can perform document.getElementById(id) and similar methods on the rendered document
1b - whilst browsers allow tags with the same ID in the same document, they shouldn’t* and might not one day - rendering a document into a separate iframe allows you to manipulate its DOM whilst playing along with the standards
2 - the iframe behaves as a sandbox for CSS, so you don’t risk upsetting your page’s CSS when rendering the document
3 - if the page you’re rendering has any document.write invocations in its JavaScript, they will overwrite your already-rendered page
4 - the document inside the iframe is a full HTML page, so has a DOCTYPE associated with it
* http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2
I thought “documentFragment” was intended for, or at least useful for, such things.