我正在尝试使用以下代码处理页面中的所有错误:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onerror = function (e, url, line) {
var data = '{"error":"' + e + '","line":"' + line + '","uri":"' + url + '","client":"' + navigator.appName + '","version":"' + navigator.userAgent + '"}';
var call = "http://myserver.com/sandbox/error.aspx?e=" + data;
var jse = document.createElement("script");
var head = document.getElementsByTagName("head")[0];
jse.setAttribute("type", "text/javascript");
jse.setAttribute("src", call);
head.appendChild(jse);
alert("fail");
return true;
}
</script>
</head>
<body>
<script type="text/javascript">
var b;
a = 5; //a is undefined
b = 5;
c = 8; //c is undefined
</script>
</body>
</html>
这有效,使用 Internet Explorer 开发人员工具 (F12) 我可以看到请求:
http://myserver.com/sandbox/jserror.aspx?e={"error":"'a' is undefined","line":"23","uri":"file:///C:/User/user/Desktop/Data/JSerror/javascript-error.htm","client":"Microsoft Internet Explorer","version":"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; Zune 4.7)"}
HTTP状态为200 OK,数据下发到服务器。问题是只有第一个错误得到处理,如果我这样做:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onerror = function (e, url, line) {
var data = '{"error":"' + e + '","line":"' + line + '","uri":"' + url + '","client":"' + navigator.appName + '","version":"' + navigator.userAgent + '"}';
var call = "http://myserver.com/sandbox/error.aspx?e=" + data;
var jse = document.createElement("script");
var head = document.getElementsByTagName("head")[0];
jse.setAttribute("type", "text/javascript");
jse.setAttribute("src", call);
head.appendChild(jse);
alert("fail");
return true;
}
</script>
</head>
<body>
<script type="text/javascript">
var b;
a = 5; //a is undefined
b = 5;
</script>
<script type="text/javascript">
c = 8; //c is undefined
</script>
</body>
</html>
然后处理来自第一个脚本标签的第一个错误和来自第二个脚本标签的第一个错误,我想处理所有错误,而不仅仅是每个脚本标签的第一个错误。
这可能吗?