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):

<iframe src="javascript:void(0);">
<html>
<head><title></title><link href='/css/style.css' rel='stylesheet' type='text/css' /></head>
<body>preview content goes here</body>
</html>
</iframe>

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 " -> &#34;
run JavaScript immediately after form field is written, picking up its contents and writing these into the iframe

<input type='hidden' id='hidden1' value=\"<html><head><title></title><link href='/css/fckeditor.css' rel='stylesheet' type='text/css' /></head><body> content </body></html>
 
<script type='text/javascript'>mydoc = document.getElementById('content1').contentWindow.document; mydoc.write(document.getElementById('hidden1').value); mydoc.close();</script>

This works really well and solved my problems.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA - answer the question below to prove you are human *

This site uses Akismet to reduce spam. Learn how your comment data is processed.