Execute JavaScript code stored as a string

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

提交回复
热议问题