How do you send console messages and errors to alert?

前端 未结 3 596
离开以前
离开以前 2020-12-09 18:28

I would like to pass errors to an alert to warn the user they made mistake in their code even if they don\'t have console open.

    var doc=(frame.contentWin         


        
3条回答
  •  半阙折子戏
    2020-12-09 19:09

    Ok so the less elegant but highly efficient way of doing this is 'refactoring' your innate console functions. Basically any error or warnings you get are being outputted there by a javascript function that is pretty similar to the familiar console.log() function. The functions that I am talking about are console.warn(), console.info() and console.error(). now let's 're-map' what each of those do:

    //remap console to some other output
    var console = (function(oldCons){
        return {
            log: function(text){
                oldCons.log(text);
                //custom code here to be using the 'text' variable
                //for example: var content = text;
                //document.getElementById(id).innerHTML = content
            },
            info: function (text) {
                oldCons.info(text);
                //custom code here to be using the 'text' variable
            },
            warn: function (text) {
                oldCons.warn(text);
                //custom code here to be using the 'text' variable
            },
            error: function (text) {
                oldCons.error(text);
               //custom code here to be using the 'text' variable
            }
        };
    }(window.console));
    
    //Then redefine the old console
    window.console = console;
    

    Now, generally I would highly advise against using something like this into production and limit it to debugging purposes, but since you are trying to develop a functionality that shows the output of the console, the lines are blurry there, so I'll leave it up to you.

提交回复
热议问题