Why is console.log an empty function on some sites in Chrome?

三世轮回 提交于 2019-11-30 11:50:05

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

console.log = function(){};

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

console.log = console.__proto__.log

Then you can do this:

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

And it should work as expected.

Developers like to put console.log() statements in their code for troubleshooting/debugging. Sometimes, they forget to take them all out when checking in production code. A simple safeguard against this is to redefine console.log() in production code to be an empty function that does nothing so even if a developer accidentally leaves one in, it won't cause any output or throw an exception when there is no console object when not running the debugger (like in IE).

Some browsers may protect against the replacing of that function by making it read-only such that it can't be overwritten in this way, but if they do that, then the console object must exist so there's still no harm from an occasional console.log() statement. The main harm of these leftover console.log() statements is in IE where it causes an exception to be thrown because the console object doesn't exist unless the debugger is being run.

Get it from an iframe:

function setConsole() {
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  console = iframe.contentWindow.console;
  window.console = console;
}

(and then call it)

setConsole()

source: https://gist.github.com/cowlicks/a3bc662b38c36483b35f74b2b54e37c0

It's a problem with console.log. try this instead:

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

This problem doesn't occur on Firefox.

I've checked on Chrome and apparently for some reason the Gmail and Twitter pages end up reassigning console.log to an empty function function () {}, so your handler gets called but it does nothing. If you try alert() instead of console.log, you'll see it working.

Interesting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!