简体   繁体   English

在页面内的 div 中显示控制台错误和警报

[英]Showing console errors and alerts in a div inside the page

I'm building a debugging tool for my web app and I need to show console errors in a div.我正在为我的 web 应用程序构建一个调试工具,我需要在 div 中显示控制台错误。 I know I can use my own made console like object and use it, but for future use I need to send all console errors to window.我知道我可以使用自己制作的控制台,如 object 并使用它,但为了将来的使用,我需要将所有控制台错误发送到 window。 Actually I want to catch console events.其实我想捕捉控制台事件。

To keep the console working:要保持控制台正常工作:

if (typeof console  != "undefined") 
    if (typeof console.log != 'undefined')
        console.olog = console.log;
    else
        console.olog = function() {};

console.log = function(message) {
    console.olog(message);
    $('#debugDiv').append('<p>' + message + '</p>');
};
console.error = console.debug = console.info =  console.log

Here's a way using closure, containing the old console log function in the scope of the new one.这是一种使用闭包的方法,在新控制台的 scope 中包含旧控制台日志 function。

console.log = (function (old_function, div_log) { 
    return function (text) {
        old_function(text);
        div_log.value += text;
    };
} (console.log.bind(console), document.getElementById("error-log")));

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):否则,如果您担心将logwarnerror彼此分开,您可以执行以下操作(改编自 MST 的回答):

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.其中#log是您的 HTML 元素。 The variable verb is one of 'log' , 'warn' , or 'error' .变量verb'log''warn''error'之一。 You can then use CSS to style the text in a distinguishable way.然后,您可以使用 CSS 以可区分的方式设置文本样式。 Note that a lot of this code isn't compatible with old versions of IE.请注意,很多代码与旧版本的 IE 不兼容。

None of the answers here consider console messages that get passed multiple parameters.这里的答案都没有考虑传递多个参数的控制台消息。 Eg console.log("Error:", "error details") ).例如console.log("Error:", "error details") )。

The function that replaces the default log function better regards all function arguments (eg by using the arguments object). The function that replaces the default log function better regards all function arguments (eg by using the arguments object). Here is an example:这是一个例子:

console.log = function() {
  log.textContent += Array.prototype.slice.call(arguments).join(' ');
}

(The Array.prototype.slice.call(...) simply converts the arguments object to an array, so it can be concatenated easily with join() .) Array.prototype.slice.call(...)只是将arguments object 转换为数组,因此可以使用join()轻松连接。)

When the original log should be kept working as well:当原始日志也应该保持工作时:

console.log = (function (old_log, log) { 
    return function () {
        log.textContent += Array.prototype.slice.call(arguments).join(' ');
        old_log.apply(console, arguments);
    };
} (console.log.bind(console), document.querySelector('#log')));

A complete solution:一个完整的解决方案:

var log = document.querySelector('#log');
['log','debug','info','warn','error'].forEach(function (verb) {
    console[verb] = (function (method, verb, log) {
        return function () {
            method.apply(console, arguments);
            var msg = document.createElement('div');
            msg.classList.add(verb);
            msg.textContent = verb + ': ' + Array.prototype.slice.call(arguments).join(' ');
            log.appendChild(msg);
        };
    })(console[verb], verb, log);
});

(An example of a framework that emits messages with multiple parameters is Video.js. But there is certainly many others.) (使用多个参数发出消息的框架的一个例子是 Video.js。但当然还有很多其他的。)

Edit: Another use of multiple parameters is the formatting capabilities of the console (eg console.log("Status code: %d", code) .编辑:多个参数的另一个用途是控制台的格式化功能(例如console.log("Status code: %d", code)

How about something as simple as:像这样简单的事情怎么样:

console.log = function(message) {$('#debugDiv').append('<p>' + message + '</p>');};
console.error = console.debug = console.info =  console.log
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <div id="logger" class="web_console"></div>

    <script type="text/javascript">

        // Overriding console object
        var console = {};

        // Getting div to insert logs
        var logger = document.getElementById("logger");

        // Adding log method from our console object
        console.log = function(text)
        {
            var element = document.createElement("div");
            var txt = document.createTextNode(text);

            element.appendChild(txt);
            logger.appendChild(element);
        }

        // testing
        console.log("Hello World...");
        console.log("WOW");

        /**
            console.log prints the message in the page instead browser console, useful to programming and debugging JS using a Android phone

        */
    </script>
</body>
</html>

I created a zero-dependency npm module for this case: console-events (surely if you're okay to use nodejs:P)我为这种情况创建了一个零依赖npm模块console-events (当然,如果你可以使用 nodejs:P)

You can add event listener like that:您可以像这样添加事件侦听器:

const { console } = require('console-events');

console.addEventListener('log', (e) => {
   e.preventDefault(); //if you need to prevent normal behaviour e.g. output to devtools console
   $('#debugDiv').append('<p>' + message + '</p>');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM