为什么在 Chrome 的某些网站上 console.log 是一个空函数?

转到 Twitter 的登录页面并在控制台中输入以下内容:

Go to Twitter's login page and type the following in the console:

window.addEventListener('keypress', function(e){console.log('hello')}, true)

(注意:如何将第三个参数设置为 true 以启用事件捕获.这会导致事件在被子元素消费之前首先被窗口拦截.)

(NOTE: how the third parameter is set to true which enables event capture. This causes events to be intercepted first by the window before being consumed by a child element.)

尝试按一些键.注意 hello 是如何不输出到控制台的.为 keydownkeyup 添加事件监听器不会改变任何东西.

Try pressing some keys. Notice how hello isn't output to the console. Adding an event listener for keydown or keyup doesn't change anything.

hello 将在大多数网站上获得输出,但不会在 Twitter 或 Gmail 等网站上获得输出.

hello will get output on most websites, but not on sites like Twitter or Gmail.

为什么?是什么阻止了事件侦听器?

Why? What's stopping the event listener?

似乎在 Firefox 上按预期工作.但不是铬.为什么 Chrome 没有按预期触发事件侦听器?

Seems to work as expected on Firefox. But not Chrome. Why isn't Chrome firing the event listener as expected?

编辑 2:正如下面的一些人所推断的,console.log 是 Chrome 上的一个空函数,用于 Twitter 和 Gmail 等网站.这是为什么呢?

EDIT 2: As deduced by a few people below, console.log is an empty function on Chrome for sites like Twitter and Gmail. Why is that?

推荐答案

因为那些网站已经专门设置了(显然是针对webkit):

Because those sites have specifically set (for webkit apparently):

console.log = function(){};

但是,在 Chrome 中,您可以通过在控制台中发出以下命令来恢复原始 log() 功能:

However, in Chrome you can restore the original log() functionality by issuing this command in console:

console.log = console.__proto__.log

那么你可以这样做:

window.addEventListener('keypress', function(e){console.log('hello')}, true)

它应该按预期工作.

相关文章