Appropriate method for executing JavaScript from user input?

I need to create a web application that allows the user to inject javascript code, and then the code is dynamically executed and somehow shows the result on the same page. The stream will be something like this:

The web page has a textarea, and under each of those textareas, there is a result div (or any span, p, doesn't matter). User enters javascript code inside text fields. It should be able to inject whatever javascript code it wants, but at the end it will call a custom function like my_application_output (some_variables_computed_from_previous_code_execution)

and then something will be displayed in the result div. Simple example: if he enters the following text in the text box:

var a = 0;


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

I don't really understand how to get started, like what technologies or system architecture I should be using. so would like to ask for some pointers here. I thought of two options (not sure if they are good)

  • Use a JavaScript function eval()

    . so I just execute the code from the textbox directly on the client side.

  • Implement a backend service using a V8 type engine. So I make an ajax call to create a backend with the content of the code, and then the codes are executed from the backend and the result is returned. Then I put the result in the result div.

Personally, I would like to go for 1) because eval () seems like a simpler solution. However, I'm not sure if there are any restrictions on this feature or if it can achieve what I want to do. Otherwise, if I need to go for the second option. Anyone can suggest an architecture for this?


source to share

1 answer

Option 1 is not only easier, but also a safer choice.

Why? Anyone who has Firebug installed in Firefox (or just the Chrome Dev tools) already has what you are asking for, although it may not be in a noobrock style. The code they write is isolated from the browser being used and nothing more.

With option 2, you are going to execute arbitrary untrusted code on the server. Let's say they understand that you are using Node.js (the most likely choice here), then run a bomb fork on their server:

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


Not to mention something more vile.

Remember that REPL stands for Read-Eval-Print-Loop, and what dynamic languages ​​have since Lisp been using to help programmers understand their languages. Eval is great if only the person the newbie can hurt is on their own.



All Articles