Featured image of post 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)

1
2
3
4
5
var prevFrame = document.getElementById('preview'),
    ipreview = prevFrame.contentDocument || prevFrame.contentWindow.document;
ipreview.open();
ipreview.write(msg); // writes the html value
ipreview.close();
comments powered by Disqus
CC-BY-NC 4.0
Built with Hugo Theme Stack