Preview HTML code in HTML page

Preview HTML code in HTML page

Use iframe to include html code and preview it.

I was trying to build an HTML wrapper with preview function. The preview module should be able to receive html code from the wrapper and preview it independently using it’s own css/js. Using iframe with scr attribute is of course one solution but it’s difficult to write into the source file everytime.

Got some hints from existing html online editors (e.g. https://www.onlinehtmleditor.net/)

first build an iframe

<iframe id="preview" frameBorder="0" />

Then use JavaScript to transfer content (textarea value or defined variable)

var prevFrame = document.getElementById('preview'),
    ipreview = prevFrame.contentDocument || prevFrame.contentWindow.document;
ipreview.open();
ipreview.write(msg); // writes the html value
ipreview.close();
Z. Lu avatar
Z. Lu
Computer biologist, amature photographer, vintage fan and web lover.
comments powered by Disqus