Wednesday, August 6th, 2008

Introducing HTML into an iframe and getting it back

Category: HTML, JavaScript, Tip

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:


  1. // put it in
  2. var doc = iframe.document;
  3. if (iframe.contentDocument)
  4.   doc = iframe.contentDocument; // For NS6
  5. else if(iframe.contentWindow)
  6.   doc = iframe.contentWindow.document; // For IE5.5 and IE6
  8. // Put the content in the iframe
  10. doc.writeln(content);
  11. doc.close();
  13. // and then get it out
  14. var storeArea = doc.getElementById("storeArea");

Posted by Dion Almaer at 11:07 am

3 rating from 44 votes


Comments feed TrackBack URI

This is really old and there is no trick. Just simple and standard DOM.

Comment by JrHames — August 6, 2008

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.

Comment by eyelidlessness — August 6, 2008

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.

Comment by jpsykes — August 6, 2008

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;

Comment by AriesBelgium — August 6, 2008

Hmm, WordPress takes away the html instead of converting it to htmlchars.

Comment by AriesBelgium — August 6, 2008

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


Comment by jnthnlstr — August 7, 2008

I thought “documentFragment” was intended for, or at least useful for, such things.

Comment by shadedecho — August 7, 2008

Leave a comment

You must be logged in to post a comment.