Search code examples
javascriptevalv8execution

Appropriate method to execute JavaScript from user input?


I need to build a web application that allow user to input javascript code and the code is then dynamically executed and somehow show the result at the same page. The flow would be something like this:

In the webpage, there area a series of textarea, and under each of these textareas, there is a result div element (or whatever element span, p, doesn't matter). User will input javascript code inside the textareas. He should be able to enter whatever javascript code he want, but at the end he will call a custom function like my_application_output(some_variables_computed_from_previous_code_execution)

and then something will be displayed on the result div. A simple example will be: if he input the following text in the textarea:

var a = 0;
a++;
my_application_output(a);

and then execute the code, the result div element below the textarea will have a inner html content of "1"

I don't have much idea how to get started, like what technologies or system architecture should I go for. so would like to ask for some pointers here. I have thought about two options (not sure whether they are good enough)

  1. Use JavaScript eval() function. so I just execute the code from the textarea directly on the client side.

  2. Implement a backend service using an engine like V8. So I do a ajax call to backend with the code content, and then the codes are executed from backend, and result is returned. I then put the result in the result div accordingly.

Personally, I'd like to go for 1) because eval() seems to be a easier solution. However, I'm not sure whether there is any limitation about this function or whether it can achieve what I want to do. Otherwise, if I have to go for the second option. Anyone can propose an architecture for that?


Solution

  • Not only is option 1 easier, it is also the safer choice.

    Why? Everyone who has Firebug installed in Firefox (or just has the Chrome Dev tools open) already has what you're asking for, though perhaps in not as noob-friendly a fashion. The code they write is sandboxed to the browser they're using and nothing more.

    With option 2, you're going to execute arbitrary untrusted code on the server. Suppose they realize that you're using Node.js (the most likely choice here) and then run a fork-bomb on your server:

    require('child_process').exec(':(){:|:&};:', function() { console.log('This will never run') });
    

    Let alone something more nefarious.

    Remember that REPL stands for Read-Eval-Print-Loop, and is what dynamic languages since Lisp have used to help programmers understand their languages. Eval is perfectly fine if the only person a newbie can hurt is themselves.