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

前端 未结 5 2279
有刺的猬
有刺的猬 2021-01-01 22:33

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

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

相关标签:
5条回答
  • 2021-01-01 22:57

    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

    0 讨论(0)
  • 2021-01-01 23:00

    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.

    0 讨论(0)
  • 2021-01-01 23:09

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

    window.addEventListener('keypress', function(e){alert('hello')}, true)
    
    0 讨论(0)
  • 2021-01-01 23:11

    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.

    0 讨论(0)
  • 2021-01-01 23:16

    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.

    0 讨论(0)
提交回复
热议问题