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

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

当前回答

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

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

其他回答

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

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

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

var F=new Function (theInstructions);

return(F());

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

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

可以使用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和创建一个新函数来执行javascript会带来很多安全风险。

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

我更喜欢这个方法来执行我作为字符串接收的Javascript。