是否可以捕获发生在屏幕上的所有事件/错误/日志console
并将它们显示在屏幕上的元素中?这可以用 JavaScript 完成吗?
问问题
2899 次
3 回答
4
您始终可以覆盖这些console
方法,也可以点击window
'serror
事件。这是一个覆盖的示例,包括监听error
事件。
(function () {
"use strict";
var methods, generateNewMethod, i, j, cur, old, addEvent;
if ("console" in window) {
methods = [
"log", "assert", "clear", "count",
"debug", "dir", "dirxml", "error",
"exception", "group", "groupCollapsed",
"groupEnd", "info", "profile", "profileEnd",
"table", "time", "timeEnd", "timeStamp",
"trace", "warn"
];
generateNewMethod = function (oldCallback, methodName) {
return function () {
var args;
alert("called console." + methodName + ", with " + arguments.length + " argument(s)");
args = Array.prototype.slice.call(arguments, 0);
Function.prototype.apply.call(oldCallback, console, arguments);
};
};
for (i = 0, j = methods.length; i < j; i++) {
cur = methods[i];
if (cur in console) {
old = console[cur];
console[cur] = generateNewMethod(old, cur);
}
}
}
window.onerror = function (msg, url, line) {
alert("Window error: " + msg + ", " + url + ", line " + line);
};
}());
console.log("ahh", "fdsa");
console.warn("f");
(function () {
throw new Error("asdf");
}());
演示:http: //jsfiddle.net/HfPJ8/
于 2013-06-18T21:45:53.280 回答
0
您可以编写自己的日志框架或使用可用的日志框架,例如log4javascript,但我认为它们中的任何一个都不能从控制台重定向输出,您必须使用它try..catch
来捕获错误或全局错误侦听器(这在浏览器中不是很可靠),然后通过框架的方法记录它们。
于 2013-06-18T21:41:15.223 回答
0
将代码放在 body 标记的顶部,或 html 页面中的任何位置。
<ul id="console-container"></ul>
<script>
(function(){
let printOnScreen = function (...args) { // adds <li> on "console-container"
let node = document.createElement("LI");
let textnode = document.createTextNode("console: " + args.join(" - ") );
node.appendChild(textnode);
window.document.getElementById("console-container").appendChild(node);
};
let methods = Object.keys(console) //get all console methods
for (i = 0, j = methods.length; i < j; i++) {
console[methods[i]] = printOnScreen; //override all methods
}
window.onerror = function (...args) { // catch all unhandled exceptions
printOnScreen(args)
}
})();
</script>
于 2020-02-07T17:06:50.460 回答