评估与 Web 控制台

Eval vs web console

如果您评估用户生成的代码,我总是听到和读到 "Eval is evil"。

但与在 Web 控制台中键入代码有何不同?还有哪些选择?

我知道网络上到处都是像我这样的问题。但是我无法理解我读到的内容,对不起。如果你能帮助我,那就太好了。我记得我读过一些关于作用域的内容,那么 eval() 和 Web 控制台有不同的作用域吗?如果是,为什么这会使 Web 控制台更安全?

感谢您的建议!
达斯·穆恩

编辑:为什么通过 Web 控制台/通过 eval 传递代码是危险的?我虽然js会在客户端执行?

中执行代码都不安全;两者都可能导致 XSS 攻击。
Web 控制台在这方面与评估代码一样容易受到攻击。

但是,它们确实有不同的作用域。

eval() 根据调用方式在全局范围或局部范围内工作:

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

Web 控制台在页面 window 范围内执行代码。

有趣的是,浏览器控制台 has a different scopeWeb 控制台, 运行 浏览器下的 chrome window:

Similarly, you can execute JavaScript expressions using the Browser Console. But while the Web Console executes code in the page window scope, the Browser Console executes them in the scope of the browser's chrome window.