Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting web browser console messages

Tags:

javascript

I'm working on a web app that's going to be rolling out to a few users for testing. There's obviously going to be bugs, so I'd like to capture them to make it easier to develop fixes. Is there a way for me to intercept any console messages (both browser/js errors and messages generated with console.log) in my web app, so I can send them to a logging service on the server and have them available for debugging?

like image 550
sslepian Avatar asked Jul 26 '11 18:07

sslepian


1 Answers

Yes.

Intercepting console.log() calls:

console['log'] = function(msg){
    // do wahtever you need with msg here
}

Intercepting errors (so called diaper anti-pattern):

try {
    // your app's code
} catch(err) {
    // do what you to do in case of error need here
}

Here is the proof: jsfiddle.

However, I would suggest creating your own function, that will handle console.log() purpose and could be switched off on production. Plus, it will work properly (that means: won't throw errors), when the browser does not support console.log() calls. This could look like that:

window['log'] = function(msg){
    if (typeof console != 'undefined' && typeof console.log != 'undefined'){
        console.log(msg);
    }
}
like image 105
Tadeck Avatar answered Sep 25 '22 09:09

Tadeck