我如何执行一些JavaScript是一个字符串?

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

当前回答

eval(s);

记住,eval是非常强大的,但是非常不安全。您最好确信您正在执行的脚本是安全的,用户是不可更改的。

其他回答

有点像@Hossein Hajizadeh alerady说的,不过更详细:

有一个替代eval()的方法。

函数setTimeout()被设计为在毫秒间隔后执行一些东西,而要执行的代码恰好格式化为字符串。

它是这样工作的:

ExecuteJavascriptString ();//只是为了运行它 ExecuteJavascriptString()函数 { Var s = "alert('hello')"; setTimeout (s, 1); }

1表示它将在执行字符串前等待1毫秒。

这可能不是最正确的方法,但它确实有效。

eval函数将对传递给它的字符串求值。

但是eval的使用是超级危险和缓慢的,所以要谨慎使用。

该方法避免使用潜在风险的eval,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。

执行字符串命令

function string_cmd(sCmd) {
    new Function(sCmd)();
}

求字符串表达式的值

function string_exp(sCmd) {
    return Function(
        `'use strict'; 
        return (${sCmd})`
        )();
}

用法:

const result = string_exp("2+2");

string_cmd("alert(result)");

https://codepen.io/johnaweiss/pen/mdKpyZL

如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - cmd=你的代码 —InterVal=运行延迟时间

 function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
//sample
ExecStr("alert(20)",500);

同时使用eval和创建一个新函数来执行javascript会带来很多安全风险。

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

我更喜欢这个方法来执行我作为字符串接收的Javascript。