1

I'm developing an app, which allows a user to enter JavaScript and HTML in ace-editor. The layout will be something like below:

https://drive.google.com/file/d/1QU14HPp-cAryomkEPbwFQ9UbLye3ZQzw/view?usp=drivesdk

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.

zero_cool
  • 3,960
  • 5
  • 39
  • 54

2 Answers2

0

Ace-Editor is just a editor . if you want to execute your code you need to implement yourself...

try Vm for execute js code in nodejs

sathish kumar
  • 1,477
  • 1
  • 11
  • 18
0

If everything except JavaScript execution worked as intended, the issue was likely that changing innerHTML (or using DataURL, for that matter) will not automatically [re-]execute <script>s - you would need to call iframe.contentWindow.eval, or append one-time replicas of them to document.head (see here)

YellowAfterlife
  • 2,967
  • 1
  • 16
  • 24