Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening console.log

I want to set a listener for console.log() and do something with the message without preventing the default behaviour. So, the console of the dev tools should get the message as well. Any ideas?

like image 508
Peter Efrans Avatar asked Jun 23 '11 14:06

Peter Efrans


People also ask

What is console log used for?

The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.

What is inside a console log?

The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.


2 Answers

Never tried this in a webpage, but it work in a browser plugin (where javascripts rights are are not the same for security reasons).

You could definitively go for something like this :

(function(){

    var originallog = console.log;

    console.log = function(txt) {
        // Do really interesting stuff
        alert("I'm doing interesting stuff here !");

        originallog.apply(console, arguments);
    }

})();

The funny thing in javascript is that function are objects too :D

like image 138
deadalnix Avatar answered Oct 13 '22 03:10

deadalnix


This is a small hack, but I'm not sure there is a better solution:

console._log_old = console.log
console.log = function(msg) {
    alert(msg);
    console._log_old(msg);
}
like image 27
Gabi Purcaru Avatar answered Oct 13 '22 05:10

Gabi Purcaru