Showing console errors and alerts in a div inside the page

后端 未结 7 743
梦毁少年i
梦毁少年i 2020-12-02 09:10

I\'m building a debugging tool for my web app and I need to show console errors in a div. I know I can use my own made console like object and use it, but for future use I n

7条回答
  •  难免孤独
    2020-12-02 09:39

    Else, if you were concerned at keeping log, warn and error separate from one another, you could do something like this (adapted from MST's answer):

    var log = document.querySelector('#log');
    
    ['log','warn','error'].forEach(function (verb) {
        console[verb] = (function (method, verb, log) {
            return function (text) {
                method(text);
                // handle distinguishing between methods any way you'd like
                var msg = document.createElement('code');
                msg.classList.add(verb);
                msg.textContent = verb + ': ' + text;
                log.appendChild(msg);
            };
        })(console[verb].bind(console), verb, log);
    });
    

    where #log is your HTML element. The variable verb is one of 'log', 'warn', or 'error'. You can then use CSS to style the text in a distinguishable way. Note that a lot of this code isn't compatible with old versions of IE.

提交回复
热议问题