我如何执行一些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')?
}
当前回答
可以使用mathjs
来自上述链接的片段:
// evaluate expressions
math.evaluate('sqrt(3^2 + 4^2)') // 5
math.evaluate('sqrt(-4)') // 2i
math.evaluate('2 inch to cm') // 5.08 cm
math.evaluate('cos(45 deg)') // 0.7071067811865476
// provide a scope
let scope = {
a: 3,
b: 4
}
math.evaluate('a * b', scope) // 12
math.evaluate('c = 2.3 + 4.5', scope) // 6.8
scope.c
作用域是任何对象。因此,如果将全局作用域传递给evaluate函数,就可以动态地执行alert()。
此外,mathjs是比eval()更好的选择,因为它运行在沙箱中。
方法注入恶意JavaScript代码 表达式解析器。mathjs的表达式解析器提供了一个沙盒 环境来执行表达式,这应该是不可能的。 尽管有可能存在未知的安全漏洞, 所以一定要小心,尤其是在允许服务器端使用时 任意表达式的执行。
新版本的mathjs不使用eval()或Function()。
解析器会主动阻止对JavaScripts内部eval和 这些是安全攻击的主要原因。Mathjs 版本4及更新版本没有在底层使用JavaScript的eval。 版本3和更老的版本确实使用eval进行编译步骤。这不是 直接造成安全问题,但可能会导致更大的攻击 表面。
其他回答
eval函数将对传递给它的字符串求值。
但是eval的使用是超级危险和缓慢的,所以要谨慎使用。
不确定这是不是作弊:
window.say = function(a) { alert(a); };
var a = "say('hello')";
var p = /^([^(]*)\('([^']*)'\).*$/; // ["say('hello')","say","hello"]
var fn = window[p.exec(a)[1]]; // get function reference by name
if( typeof(fn) === "function")
fn.apply(null, [p.exec(a)[2]]); // call it with params
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!!')
如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - 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,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。
执行字符串命令
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