Javascript 在页面内的 div 中显示控制台错误和警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6604192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing console errors and alerts in a div inside the page
提问by Mohsen
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 need to send all console errors to window. Actually I want to catch console events.
我正在为我的 Web 应用程序构建一个调试工具,我需要在 div 中显示控制台错误。我知道我可以像对象一样使用我自己制作的控制台并使用它,但是为了将来使用,我需要将所有控制台错误发送到 window.console 。其实我想捕捉控制台事件。
回答by jzilla
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
回答by MST
Here's a way using closure, containing the old console log function in the scope of the new one.
这是一种使用闭包的方法,在新的范围内包含旧的控制台日志功能。
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")));
回答by Micah Henning
Else, if you were concerned at keeping log, warnand errorseparate from one another, you could do something like this (adapted from MST's answer):
否则,如果您担心保持log,warn并且error彼此分开,您可以做这样的事情(改编自 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 #logis your HTML element. The variable verbis 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.
#log你的 HTML 元素在哪里。变量verb是一个'log','warn'或'error'。然后,您可以使用 CSS 以可区分的方式设置文本样式。请注意,此代码中有很多与旧版本的 IE 不兼容。
回答by Peter Lyons
How about something as simple as:
像这样简单的事情怎么样:
console.log = function(message) {$('#debugDiv').append('<p>' + message + '</p>');};
console.error = console.debug = console.info = console.log
回答by jox
None of the answers here consider console messages that get passed multiple parameters. E.g. console.log("Error:", "error details")).
这里的答案都没有考虑传递多个参数的控制台消息。例如console.log("Error:", "error details"))。
The function that replaces the default log function better regards all function arguments (e.g. by using the argumentsobject). Here is an example:
替换默认日志函数的函数更好地考虑所有函数参数(例如,通过使用arguments对象)。下面是一个例子:
console.log = function() {
log.textContent += Array.prototype.slice.call(arguments).join(' ');
}
(The Array.prototype.slice.call(...)simply converts the argumentsobject to an array, so it can be concatenated easily with join().)
(Array.prototype.slice.call(...)简单地将arguments对象转换为数组,因此可以轻松地将其与 连接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 (e.g. console.log("Status code: %d", code).
编辑:多个参数的另一个用途是控制台的格式化功能(例如console.log("Status code: %d", code).
回答by Optimaz ID
<!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>
回答by Jimmy Recard
I created a zero-dependency npmmodulefor 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>');
})

