Skip to content

noGlobalEval

诊断类别:lint/security/noGlobalEval

¥Diagnostic Category: lint/security/noGlobalEval

自从:v1.5.0

¥Since: v1.5.0

来源:

¥Sources:

禁止使用全局 eval()

¥Disallow the use of global eval().

eval() 函数将传递的字符串评估为 JavaScript 代码。执行的代码可以在调用函数的范围内访问和改变变量。

¥The eval() function evaluates the passed string as a JavaScript code. The executed code can access and mutate variables in the scope where the function is called.

eval() 的使用会暴露给 安全风险和性能问题。如果执行的代码以某种方式受到恶意方的影响,那么你最终可能会以调用者的权限执行恶意代码。此外,在现代 JavaScript 解释器中,更改调用者范围内的变量成本很高。

¥The use of eval() exposes to security risks and performance issues. If the executed code is somehow affected by a malicious party, then you may end up executing malicious code with the privileges of the caller. Moreover, changing variables in the caller’s scope is expensive in modern JavaScript interpreters.

¥Examples

¥Invalid

eval("var a = 0");
code-block.js:1:1 lint/security/noGlobalEval ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

eval() exposes to security risks and performance issues.

> 1 │ eval(“var a = 0”);
^^^^
2 │

See the MDN web docs for more details.

Refactor the code so that it doesn’t need to call eval().

(0, globalThis.eval)("var a = 0")
code-block.js:1:5 lint/security/noGlobalEval ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

eval() exposes to security risks and performance issues.

> 1 │ (0, globalThis.eval)(“var a = 0”)
^^^^^^^^^^^^^^^
2 │

See the MDN web docs for more details.

Refactor the code so that it doesn’t need to call eval().

f(eval);
code-block.js:1:3 lint/security/noGlobalEval ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

eval() exposes to security risks and performance issues.

> 1 │ f(eval);
^^^^
2 │

See the MDN web docs for more details.

Refactor the code so that it doesn’t need to call eval().

const aliasedEval = eval;
code-block.js:1:21 lint/security/noGlobalEval ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

eval() exposes to security risks and performance issues.

> 1 │ const aliasedEval = eval;
^^^^
2 │

See the MDN web docs for more details.

Refactor the code so that it doesn’t need to call eval().

¥Valid

function f(eval) {
eval("let a = 0;");
}

该规则无法检测全局对象被别名的情况:

¥The rule is not able to detect cases where the global object is aliased:

let foo = globalThis;
foo.eval("let a = 0;");

¥Related links