5

I'm trying to execute JavaScript from plain text (from being entered by a client). I also need a way to see if the executed code works or not (if it does, then it does, otherwise, it needs to spit out a non-variable error message).

Thanks if you can! The stuff that will be executed would be short strings such as:

echo("a","b")
Chris
  • 1,416
  • 18
  • 29
Freesnöw
  • 30,619
  • 30
  • 89
  • 138

2 Answers2

8

You can use eval and wrap around try-catch.

try
  {
    eval(code);
  }
catch(err)
  {
  //Handle errors here
  }
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • For better security, check out some JavaScript sandboxing techniques: http://stackoverflow.com/questions/195149/is-it-possible-to-sandbox-javascript-running-in-the-browser – kizzx2 May 13 '11 at 17:45
5

Are you saying you just need a try/catch statement?

https://developer.mozilla.org/en/JavaScript/Reference/Statements/try...catch

RwwL
  • 3,298
  • 1
  • 23
  • 24