Software As She’s Developed

Mahemoff’s Podcast/Blog – Web, Programming, Usability from the Author of ‘Ajax Design Patterns’ (AjaxPatterns.org)

Software As She’s Developed header image 2

Injecting HTML into an IFrame

August 5th, 2008 · 20 Comments · SoftwareDev

Welcome to Mahemoff's blog on web development, UX, and software development. I most recently worked in developer relations at Google, focusing on Chrome and HTML5, and am now busy baking a few apps independently.

Walking through Tiddlywiki source (write-up to follow), I noticed some interesting code in TiddlyWiki.js, importTiddlyWiki function.

The code takes a string and injects into an IFrame. I had talked to Jon a little while ago about a similar problem and was wondering about it ever since. The technique here looks like this:

It wraps the text with tags to make it an HTML document:

JAVASCRIPT:
  1. var content = "<html><body>" + text + "</body></html>";


It then introduces a new iframe to the page.

JAVASCRIPT:
  1. var iframe = document.createElement("iframe");
  2.     document.body.appendChild(iframe);


Now comes the tricky part. You would think you could just create a new iframe element and set its innerHTML, but with iframes you must use an internal doc ument property.

JAVASCRIPT:
  1. var doc = iframe.document;
  2.     if(iframe.contentDocument)
  3.         doc = iframe.contentDocument; // For NS6
  4.     else if(iframe.contentWindow)
  5.         doc = iframe.contentWindow.document; // For IE5.5 and IE6
  6.     // Put the content in the iframe
  7.     doc.open();
  8.     doc.writeln(content);
  9.     doc.close();


Now the content is in our new iframe. We can then manipulate the content using standard Javascript...but ensuring a call like getElementById is executed against the iframe document, not the global document. (i.e. don't use the usual document.getElementById()).

JAVASCRIPT:
  1. // Load the content into a TiddlyWiki() object
  2.     var storeArea = doc.getElementById("storeArea");
  3. };


With this technique, you can take an arbitrary HTML string and delegate its parsing to the browser's built-in DOM engine.

Tags: ·····