Question

Creating online learning material for mathematics, I want to allow users of my website to define (mathematical) functions, which are, by definition, side-effect free. The easiest way to achieve this is by doing the following

// ... get string entered by user and store it in variable user_code
// now build function
var user_function = eval ("(function (x) { return (" + user_code + "); })");

If the users enters x*x, user_function will contain a function that calculates the square of its argument.

Now this opens my page to cross-site scripting and malicious code.

Is there any way to avoid this, apart from writing an expression parser myself? In other words, I want to allow execution of functions in a well-defined context, for example, without the function accessing global variables.

Was it helpful?

Solution

Well, there are lots of good expression parsers that already exist for javascript, why re-invent the wheel?

I'm sure it'll be easier and safer to use something like math.js that has an expression parser built-in...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top