inoabrian
inoabrian

Reputation: 3800

How can I execute code that a user inputs into my ACE editor on my page

I am using ACE Editor as my text editor on my page and the user will type in it code.

  1. I am looking to execute code that has been entered by the user on or in the browser if possible. How do I get the input from the editor and utilize the Browsers V8 JavaScript compiler with it?

  2. I am then going to try to run it on a Node.js but first I have to learn Node :).

Upvotes: 10

Views: 8039

Answers (2)

Nick Q.
Nick Q.

Reputation: 3986

It's relatively simple to grab some user entered code and run it, with JavaScript. Essentially, you'll grab the code from ACE:

var code = editor.getValue();

Then use javascript to run it. At the simplest level you can just do:

eval(code);

However, you probably don't want to use eval(). Instead you might do something like:

// grabbed from https://stackoverflow.com/questions/6432984/adding-script-element-to-the-dom-and-have-the-javascript-run
var script = document.createElement('script');
try {
  script.appendChild(document.createTextNode(code));
  document.body.appendChild(script);
} catch (e) {
  script.text = code;
  document.body.appendChild(script);
}

This will work. However, it will still cause some problems, as then, the user code could affect your environment. In this scenario, it may not be terrible from a security perspective (unless the user can share their code), but it would be confusing. For that reason, you'll want to sandbox your code.

This answer explains sandboxing client side javascript, using window.postMessage, you could send javascript to the sandboxed iframe and have it be evaluated there.

If you wish to bring this server-side and execute Node code, you'll need to do sandboxing differently. On a server, sandboxing is much more of a concern, as the user gets to do a lot more with Javascript and could maliciously interact with your server. Luckily, there are a few sandboxes for Node that should help.

Upvotes: 18

a user
a user

Reputation: 24149

Getting code is the easy part just do code = editor.getValue()
Simply utilizing V8 compiler is easy too, create iframe and do

try {
    var result = iframeWindow.eval(code)
} catch(e) {
    // report error...
}

but this won't be very useful since it will be very easy to create infinite loops and break the page.
You can have a look at https://github.com/jsbin/jsbin/blob/master/public/js/runner/loop-protect.js#L7 to resolve loop problem.

Upvotes: 0

Related Questions