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?
Asked
Active
Viewed 9,848 times
15

Greg Guida
- 7,302
- 4
- 30
- 40

Peter Efrans
- 153
- 1
- 4
2 Answers
17
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

deadalnix
- 2,255
- 18
- 24
-
1It seems that `console.log` can't work outside of the `console` object -- perhaps it relies on the `this` variable. Also, I don't consider having functions as objects funny: it's the thing that makes this language superb. – Gabi Purcaru Jun 23 '11 at 14:30
-
You are right ! I edited my answer. We will come to a great answer both of us ;) – deadalnix Jun 23 '11 at 14:33
-
The origin file name and line number are not kept in devtool with this approach. – Nishchit Aug 01 '23 at 16:10
4
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);
}

Gabi Purcaru
- 30,940
- 9
- 79
- 95
-
The problem with that solution is that it has side effect on the global scope. A better solution is to store console._log_old in a local variable in a closure instead of in the global scope. – deadalnix Jun 23 '11 at 14:30
-
Yes it will, using apply ;) See my edited answer. Thank for making this point anyway, that was true in the previous version and I didn't noticed that in the first place. – deadalnix Jun 23 '11 at 14:34