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

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

当前回答

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!');");

其他回答

该方法避免使用潜在风险的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

使用eval函数,比如:

eval("my script here");

New Function和apply()一起工作也可以

var a=new Function('alert(1);')
a.apply(null)
new Function('alert("Hello")')();

我认为这是最好的办法。

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

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