Search code examples
javascripteval

Alternate for eval() to execute auto-generated JS code from the server


var val = 3;

var code = "var a = 5; if (a >= val) { console.log(a + ' >= ' + val); a; } else { console.log(a + ' < 3 ' + val); val; }";


console.log(eval(code));


This is the scenario where an alternative to eval() is required. The Server can send any kind of JS code which could be run on a particular block.


Solution

  • It seems to be like there is no way other than to live with eval or change the entire design of the application. Even if we look for any other alternatives, it's going to be the change in the name and syntax. But the security issues are going to be the same. Its the design of the application that JS CodeGen tool in the server will generate JS code snippets and send it via JSON in certain fields which has to be picked and executed in the front-end. But in this design, we can assure one thing that the JS code is generated only at the design time of the user and not at the runtime. Thanks for your help.