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

大兔子大兔子 提交于 2021-02-11 13:00:40

问题


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.


回答1:


Do not use eval(code) or new Function(code) as both are basically the same thing and should be blocked by CSP.

Just return your content from the server as content-type: text/javascript then get it into your page with a <script> block or import.

On the server you would have something like (pseudo code, as I don't know what tech stack you're on):

[Route("serverActionReturningCode")]
public string ActionReturningCode() 
{
    // return the content as JS
    Response.Headers.Add("content-type", "text/javascript");

    // build the response object as JS
    return "window.latestResult = {" + 
        "a: '" + a + "', " +
        "b: '" + b + "', " + 
        "generatedCode: function() { ... }" + 
    "};";
}

Then in your page:

<script src="serverActionReturningCode"></script>
<script>
     // Now the script above has run and set window.latestResult
     console.log('a', window.latestResult.a);
     console.log('b', window.latestResult.b);
     console.log('function output', window.latestResult.generatedCode());
</script>

This will let you dynamically generate JS functions on the server.

However, if you can avoid the functions and just need to pass values it is a lot simpler to use JSON instead.




回答2:


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.




回答3:


You can do it like this. Using Eval() is not recommended.

function looseJsonParse(obj){
    return Function('"use strict";return (' + obj + ')')();
}
console.log(looseJsonParse(
   "{a:(4-1), b:function(){}, c:new Date()}"
)) 

Refer this MDN article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval to dig more into it.



来源:https://stackoverflow.com/questions/52982556/alternate-for-eval-to-execute-auto-generated-js-code-from-the-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!