我如何执行一些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')?
}
当前回答
对于使用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(s);
但如果你从用户那里获取数据,这可能是危险的,尽管我想如果他们自己的浏览器崩溃了,那是他们的问题。
我正在回答类似的问题,并得到了另一个想法,如何在不使用eval()的情况下实现这一点:
const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);
在上面的代码中,您基本上创建了Blob,其中包含您的脚本,以便创建Object URL(浏览器内存中的文件或Blob对象的表示)。由于你在<script>标签上有src属性,脚本将以与从任何其他URL加载相同的方式执行。
该方法避免使用潜在风险的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和创建一个新函数来执行javascript会带来很多安全风险。
const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);
我更喜欢这个方法来执行我作为字符串接收的Javascript。
Stefan的回答延伸如下:
//Executes immediately function stringToFunctionAndExecute(str) { let func = new Function(str); return (func()); // <--- note the parenteces } //Executes when called function stringToFunctionOnly(str) { let func = new Function(str); return func; } // -^-^-^- Functions -^-^-^- (feel free to copy) // -v-v-v- Explanations -v-v-v- (run code to read easier) console.log('STEP 1, this executes directly when run:') let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')"); console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:") try { func_A(); } catch (error) { console.log('STEP ERROR, see, it failed', error) } console.log('STEP 3, but this will NOT execute directly AND you can save it for later...') let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')"); console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:") func_B(); console.log('STEP 5, TADAAAAA!!')