Writing dynamic iframe content with JavaScript

I recently had the need to put a preview of some HTML in a page for a content management system. Simply inserting the HTML into the page wasn’t any good because it would then use the pages styling and so look nothing like how it would appear once live.

I could have set about making some large changes to the CSS so that the current styling only applied to content in one division, and in the preview area a totally different set of styles applied but that would have been time consuming.

The solution I came up with was to use an iframe tag which essentially is a brand new web browser window – and put the new content into ther

The first attempt was unsuccessful (code simplified):

Unfortunately that didn’t work out. As an iframe is the container for another html document you are meant to provide a location for that document via the src attribute. Content between the iframe tags is ignored if the browser supports the tag or displayed if the browser doesn’t recognise the iframe tag. The example above gives a ‘page not found’ message in a modern browser.

The way that did work in the end was using JavaScript, and it was suprisingly simple (no external libraries required).

write iframe tag (this time empty)
write a hidden form field containing the content – be sure to escape quotes " -> "
run JavaScript immediately after form field is written, picking up its contents and writing these into the iframe

 content 

This works really well and solved my problems.