Chrome开发者工具中JavaScript的奇怪行为

8
最近,在开发者工具中使用JavaScript时,我发现了一个奇怪的特性。Chrome 接受在括号内带有运算符(加号、减号)的任意代码,并执行它,就像这样: enter image description here 我没有在其他浏览器中发现这种行为,只有在 Chrome 中。也许这是一种特性,但是它为什么会起作用?它是否可能会造成 JavaScript 引擎的问题?

我喜欢你称它为特性而不是漏洞。 - Dan
1
我写了一篇小文章介绍它:https://medium.com/@asaskevich/how-does-chrome-executes-scripts-inside-developer-tool-59a5ea8f7de2 - Alex Saskevich
2个回答

7
这是Chrome评估你的输入方式:
with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
 // your code here...
}

所以,一旦您的输入是}{,它就会变成


with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {}{} // indefined

下一个输入 }-+{ 变成了

undefined -+ {} // NaN

以此类推。


注意:该对象称为__commandLineAPI,而不是commandLineAPI。值得注意的是,该对象代表Chrome 命令行API - Ivan Akulov
@gxoptg 当然,这似乎是Redactor解析我的代码的结果 ;) - Vasili Molakhau

5
这是因为Chrome在控制台中输入的代码会被包裹在以下结构中: ```html

``` 需要注意的是,这个结构并不是真正的HTML标签,只是Chrome开发者工具用来显示文本内容的默认格式。
with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
  // Your code
}

因此,当您输入像} 10 {这样的内容时,代码的评估结果为:

with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
  } 10 {
}

这段内容涉及到it技术,描述了一个空的块、数字和一个空的结构块。

__commandLineAPI是一个内部对象,包含着Chrome命令行API


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接