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

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

当前回答

如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - 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函数,比如:

eval("my script here");

对于使用node和关心eval()上下文含义的用户,nodejs提供了vm。它创建了一个V8虚拟机,可以在一个单独的上下文中沙盒代码的执行。

更进一步的是vm2,它强化vm,允许vm运行不受信任的代码。

https://nodejs.org/api/vm.html -正式的nodejs/vm https://github.com/patriksimek/vm2 -扩展vm2

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

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

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

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

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

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

它是这样工作的:

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

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

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

您可以使用函数来执行它。例子:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());