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

前端 未结 5 2411
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题