I'm developing an app, which allows a user to enter JavaScript and HTML in ace-editor. The layout will be something like below:
Hope you get what I'm trying to do, When the user clicks the run button, the following script will be executed, but I don't know how to print the output of the code written by a user.
Run function code :
let { jsVal, htmlVal, cssVal } = this.state; // this gets all three editor values
var script = document.createElement('script');
var iframe = document.createElement('iframe');
var html = `<html><head><style>${cssVal}</style></head><body>${htmlVal} <script>${jsVal}</script></body></html>`;
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
iframe.onload = function() {
var div = iframe.contentWindow.document;
iframe.contentWindow.document.getElementsByTagName('html')[0]
};
iframe.contentWindow.document.getElementsByTagName('html')
gives me this,
<html><head><style>#editor {
background: "#ddd";
}</style></head><body><div id="editor">Thu Feb 28 2019 18:36:07 GMT+0530 (India Standard Time)</div><script>document.getElementById('editor').innerHTML = Date()</script></body></html>
I've struggled to get this executed in the output container, any clue or help on this will make my day. If you need more details I'm ready to provide them. Thanks in advance.