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.