我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
我如何执行一些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()。
W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。
你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。
您还需要知道eval()具有不同的作用域。
检查了许多复杂和混乱的脚本:
var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);
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函数,比如:
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.