Execute JavaScript code stored as a string

前端 未结 20 1047
北荒
北荒 2020-11-22 08:58

How do I execute some JavaScript that is a string?

function ExecuteJavascriptString()
{
    var s = \"alert(\'hello\')\";
    // how do I get a browser to al         


        
20条回答
  •  一个人的身影
    2020-11-22 09:09

    One can use mathjs

    Snippet from above link:

    // evaluate expressions
    math.evaluate('sqrt(3^2 + 4^2)')        // 5
    math.evaluate('sqrt(-4)')               // 2i
    math.evaluate('2 inch to cm')           // 5.08 cm
    math.evaluate('cos(45 deg)')            // 0.7071067811865476
    
    // provide a scope
    let scope = {
        a: 3,
        b: 4
    }
    math.evaluate('a * b', scope)           // 12
    math.evaluate('c = 2.3 + 4.5', scope)   // 6.8
    scope.c                                
    

    scope is any object. So if you pass the global scope to the evalute function, you may be able to execute alert() dynamically.

    Also mathjs is much better option than eval() because it runs in a sandbox.

    A user could try to inject malicious JavaScript code via the expression parser. The expression parser of mathjs offers a sandboxed environment to execute expressions which should make this impossible. It’s possible though that there are unknown security vulnerabilities, so it’s important to be careful, especially when allowing server side execution of arbitrary expressions.

    Newer versions of mathjs does not use eval() or Function().

    The parser actively prevents access to JavaScripts internal eval and new Function which are the main cause of security attacks. Mathjs versions 4 and newer does not use JavaScript’s eval under the hood. Version 3 and older did use eval for the compile step. This is not directly a security issue but results in a larger possible attack surface.

提交回复
热议问题