1

I've been hunting around Google and various JavaScript websites, but I've yet to find an answer for this. Is there any way that I could use JavaScript/JQuery to monitor events such as console.log()?

For example, I'd like to trigger an even when a separate, cumbersome-to-deal with script calls console.log('foo'); When using any web inspector with a JavaScript console, it's easy to see foo pop up when the script logs it, but is there a way I can hook that event with a different script?

RalphORama
  • 355
  • 1
  • 3
  • 11

2 Answers2

6

Code borrowed from Can I extend the console object (for rerouting the logging) in javascript?:

(function() {
    var exLog = console.log;
    console.log = function(msg) {
        exLog.apply(console, arguments);
        alert(msg);
    }
})()

This should allow you to do just about anything when console.log() has been executed, as long as this code runs before console.log() is executed.

Community
  • 1
  • 1
Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32
  • ... as long as this function executes before the 'cumbersome' script uses `console.log` – jasonscript Mar 26 '15 at 04:17
  • Do you know the scope of this function? I have it in one script, but it doesn't seem to be catching logs from another. Also, the other script is using `window.console.log` to log data, could that be causing an issue? – RalphORama Mar 26 '15 at 04:28
  • Check out this fiddle: http://jsfiddle.net/BenjaminRay/goLwyww6/ As long as you execute the code first, you should be ok. Are you calling it from a jQuery ready or somewhere that fires as soon as the DOM is ready? – Benjamin Ray Mar 26 '15 at 04:34
2

While you cannot extend console, you can wrap each of it's methods. The code below intercepts every logging method and records each call in a variable called log.

var actualConsole = window.console;
var c = window.console = {};
var log={};
for (var m in actualConsole){
    if (typeof console[m] ==='object'){
        c[m]=console[m];
    }else if (typeof actualConsole[m] ==='function'){
        c[m]=function () {
            var args = Array.prototype.slice.call(arguments);
            log[this]=log[this]||[];
            log[this].push(args);        
            actualConsole[this].apply(actualConsole,args);
        }.bind(m);
    }// else - nothing else expected
}

console.log('log',1);
console.log('log',2);
console.error('error',1);
console.warn('warn',1);

actualConsole.log('log:',log);

Log looks like:

{"log":[["log",1],["log",2]],"error":[["error",1]],"warn":[["warn",1]]}
Remento
  • 927
  • 4
  • 6