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

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

当前回答

Eval应该这样做。

eval(s);

其他回答

对于使用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.

使用eval函数,比如:

eval("my script here");

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

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

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

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

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