Execute JavaScript code stored as a string

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

    Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.

    function ExecuteJavascriptString()
    {
        var s = "alert('hello')";
        eval(s);
    }
    
    0 讨论(0)
  • 2020-11-22 09:12
    eval(s);
    

    But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.

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

    With eval("my script here") function.

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

    A bit like what @Hossein Hajizadeh alerady said, though in more detail:

    There is an alternative to eval().

    The function setTimeout() is designed to execute something after an interval of milliseconds, and the code to be executed just so happens to be formatted as a string.

    It would work like this:

    ExecuteJavascriptString(); //Just for running it
    
    function ExecuteJavascriptString()
    {
        var s = "alert('hello')";
        setTimeout(s, 1);
    }

    1 means it will wait 1 millisecond before executing the string.

    It might not be the most correct way to do it, but it works.

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

    Checked this on many complex and obfuscated scripts:

    var js = "alert('Hello, World!');" // put your JS code here
    var oScript = document.createElement("script");
    var oScriptText = document.createTextNode(js);
    oScript.appendChild(oScriptText);
    document.body.appendChild(oScript);
    
    0 讨论(0)
  • 2020-11-22 09:16
    new Function('alert("Hello")')();
    

    I think this is the best way.

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