Is there a way in JavaScript to listen console events?

前端 未结 6 2365
悲&欢浪女
悲&欢浪女 2020-12-05 04:53

I\'m trying to write handler for uncaught exceptions and browser warnings in Javascript. All errors and warnings should be sent to server for later review.

Handled e

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 05:47

    I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.

    You can redefine the behavior of each function of the console (and for all browsers) like this:

    // define a new console
    var console = (function(oldCons){
        return {
            log: function(text){
                oldCons.log(text);
                // Your code
            },
            info: function (text) {
                oldCons.info(text);
                // Your code
            },
            warn: function (text) {
                oldCons.warn(text);
                // Your code
            },
            error: function (text) {
                oldCons.error(text);
                // Your code
            }
        };
    }(window.console));
    
    //Then redefine the old console
    window.console = console;
    

提交回复
热议问题