javascriptfunctionevalevaluationexpression-evaluation

Proper way to evaluate code


So I'm building a small app where you can evaluate some pieces of JavaScript code, but I'm having a huge "moral" problem:

Initially I wanted to use eval, but I found out about its dangers, so I quickly looked for an alternative.

The closest thing I could find was the function constructor, but for one thing it doesn't evaluate simple pieces of code, such as 2 + 3, since it needs a return statement, whereas eval doesn't, and it's also not that much better security-wise than eval (at least from what I've gathered).

Are there any other ways to evaluate a string as if it were code?


Solution

  • If you want to evaluate JavaScript code, use eval. Is it dangerous? Yes. But that's only because evaluating JavaScript is dangerous. There's no safe way to evaluate JavaScript. If you want to evaluate JavaScript, use eval.

    Take every security precaution possible. It's impossible to know what security precautions you should take without knowing more details on what you want to support and how you plan to implement it.

    This may be useful:

    Is It Possible to Sandbox JavaScript Running In the Browser?

    https://github.com/google/caja