1

On a live website, I've previously changed console.log to be:

var console = {};
console.log = function () {};

With this code always executing, is it possible to reinstate the console functionality after this code, and if so, how?

It's needed, since the site is live. But I need to do further development, without making any updates to the live site. It's hard without console logging/information.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Gareth
  • 92
  • 8
  • No, you can't because by overwriting `console` you lose its original value. You need to cache that value somewhere in advance. – Angel Politis Jul 16 '19 at 08:30
  • Why would you overwrite the default behavior of `console` in the first place? – Ivar Jul 16 '19 at 08:30
  • 1
    @Ivar, since it's a large project, and having used console.log for debugging, I chose to overwrite console in production. – Gareth Jul 16 '19 at 08:46
  • so no solution at all? is this how you shutdown console? – Hebe Aug 24 '22 at 12:47

2 Answers2

4

If that code is not running on the top level, because console is on window, you can just reference window.console.log, eg:

(() => {
  var console = {};
  console.log = window.console.log;
  console.log('foo');
  // or, just reference window:
  window.console.log('bar');
})();

If the code is running on the top level and you're using const or let (rather than ES5 var), you can do the same thing:

const console = {};
console.log = window.console.log;
console.log('foo');

Otherwise, you'll have to save a reference to console.log before you reassign console with var:

var log = console.log;
var console = {};
console.log = log;
log('foo');

But it's probably not a great idea to create/overwrite built-in global variables like that unless absolutely necessary - the IIFE in the first snippet is probably preferable.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

I know this is 1 year and 8 months old by the time I write this, but I happened to figure out a good workaround solution.

You can set a global variable that will get the window.console object when the website loads and another global variable called "console" to get the old console state whenever you want.

var oldConsole = window.console;
var console = {};

So when you need to reset the console to its normal functionality, you simply do:

console = oldConsole.log; // since it's 'window.console.log'
console.log('Hello, world!'); // this output will now display on devtools with its default configuration