下面三个方法,复制粘贴即可!
//debug函数,msg可以自定义调试提示信息,variable这个可以添加需要查看的变量等其他值
function debug(msg,variable) {
if(typeof variable=="object"){
variable = JSON.stringify(variable);
}
var $ = function(id) {
return typeof id == "string" ? document.getElementById(id) : id;
};
var info = document.createElement("p");
info.style.cssText = "border:1px solid red;margin:5px auto;";
//防止特殊符号被转义,影响调试
info.innerHTML = htmlspecialchars('' + msg + (variable==undefined?"": '--->'+variable ));
if (!$("debugdiv")) {
var div = document.createElement("div");
div.id = "debugdiv";
div.style.cssText = "height:auto;width:400px;left:50px;top:20px;font-family:serif;font-size:24px;text-align:center;position:absolute;background-color:#fff;color:#000;border:2px solid red;word-wrap:break-word;padding:10px;z-index:1000;";
div.appendChild(info);
document.body.appendChild(div);
} else {
$("debugdiv").appendChild(info);
}
}
//过滤特殊字符的函数
function htmlspecialchars(c, h, g, b) {
var e = 0, d = 0, f = false;
if (typeof h === "undefined" || h === null) {
h = 2;
}
c = c.toString();
if (b !== false) {
c = c.replace(/&/g, "&");
}
c = c.replace(//g, ">");
var a = {ENT_NOQUOTES: 0,ENT_HTML_QUOTE_SINGLE: 1,ENT_HTML_QUOTE_DOUBLE: 2,ENT_COMPAT: 2,ENT_QUOTES: 3,ENT_IGNORE: 4};
if (h === 0) {
f = true;
}
if (typeof h !== "number") {
h = [].concat(h);
for (d = 0; d < h.length; d++) {
if (a[h[d]] === 0) {
f = true;
} else {
if (a[h[d]]) {
e = e | a[h[d]];
}
}
}
h = e;
}
if (h & a.ENT_HTML_QUOTE_SINGLE) {
c = c.replace(/'/g, "'");
}
if (!f) {
c = c.replace(/"/g, """);
}
return c;
}
//捕捉错误信息并打印
window.onerror = function(msg, url, line, col, error) {
// 直接将错误打印到控制台
debug("异常信息:"+msg);
debug("文件地址:"+url);
debug("错误行数:"+line);
debug("错误列数: ",col);
debug("错误详情:"+error);
// 方便在未打开控制台的时候,记录错误对象
//window.demoError = arguments
}
例子:
//错误函数 未定义x/y
var m = x + y;
效果如下: