Search code examples
javascriptdebuggingconsole

Intercept calls to console.log in Chrome


I have a script that I can't change that makes a lot of console.log calls. I want to add another layer and respond if the calls contain certain strings. This works in Firefox, but throws an "Illegal invocation" error in Chrome on the 4th line:

var oldConsole = {};
oldConsole.log = console.log;
console.log = function (arg) {
    oldConsole.log('MY CONSOLE!!');
    oldConsole.log(arg);
}

Any ideas how to get around that? I also tried cloning the console...


Solution

  • You need to call console.log in the context of console for chrome:

    (function () {
      var log = console.log;
      console.log = function () {
        log.call(this, 'My Console!!!');
        log.apply(this, Array.prototype.slice.call(arguments));
      };
    }());
    

    Modern language features can significantly simplify this snippet:

    {
      const log = console.log.bind(console)
      console.log = (...args) => {
        log('My Console!!!')
        log(...args)
      }
    }