Execute JavaScript code stored as a string

前端 未结 20 820
北荒
北荒 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:04

    The eval function will evaluate a string that is passed to it.

    But the use of eval can be dangerous, so use with caution.

    Edit: annakata has a good point -- Not only is eval dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.

    0 讨论(0)
  • 2020-11-22 09:04

    Use eval().

    W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.

    You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.

    You'll also want to know that eval() has a different scope.

    0 讨论(0)
  • 2020-11-22 09:09
    function executeScript(source) {
        var script = document.createElement("script");
        script.onload = script.onerror = function(){ this.remove(); };
        script.src = "data:text/plain;base64," + btoa(source);
        document.body.appendChild(script);
    }
    
    executeScript("alert('Hello, World!');");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:10

    If you want to execute a specific command (that is string) after a specific time - cmd=your code - InterVal=delay to run

     function ExecStr(cmd, InterVal) {
        try {
            setTimeout(function () {
                var F = new Function(cmd);
                return (F());
            }, InterVal);
        } catch (e) { }
    }
    //sample
    ExecStr("alert(20)",500);
    
    0 讨论(0)
  • 2020-11-22 09:12

    Try this:

      var script = "<script type='text/javascript'> content </script>";
      //using jquery next
      $('body').append(script);//incorporates and executes inmediatelly
    

    Personally, I didn't test it but seems to work.

    0 讨论(0)
提交回复
热议问题