gpt4 book ai didi

JavaScript 全局事件机制

转载 作者:IT老高 更新时间:2023-10-28 11:04:13 29 4
gpt4 key购买 nike

我想捕获每个抛出的未定义函数错误。 JavaScript 中是否有全局错误处理工具?用例是从 flash 中捕获未定义的函数调用。

最佳答案

如何捕获未处理的 Javascript 错误

分配window.onerror事件到事件处理程序,例如:

<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;

// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);

// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues

var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
</script>

如代码中所注释,如果返回值为window.onerrortrue那么浏览器应该禁止显示警告对话框。

window.onerror 事件何时触发?

简而言之,当 1.) 存在未捕获的异常或 2.) 发生编译时错误时,会引发该事件。

uncaught exceptions

  • throw "some messages"
  • call_something_undefined();
  • cross_origin_iframe.contentWindow.document;, a security exception

compile error

  • <script>{</script>
  • <script>for(;)</script>
  • <script>"oops</script>
  • setTimeout("{", 10);, it will attempt to compile the first argument as a script

支持 window.onerror 的浏览器

  • Chrome 13+
  • 火狐6.0+
  • Internet Explorer 5.5+
  • Opera 11.60+
  • Safari 5.1+

截图:

将上面的 onerror 代码添加到测试页面后的示例:

<script type="text/javascript">
call_something_undefined();
</script>

Javascript alert showing error information detailed by the window.onerror event

AJAX 错误报告示例

var error_data = {
url: document.location.href,
};

if(error != null) {
error_data['name'] = error.name; // e.g. ReferenceError
error_data['message'] = error.line;
error_data['stack'] = error.stack;
} else {
error_data['msg'] = msg;
error_data['filename'] = filename;
error_data['line'] = line;
error_data['col'] = col;
}

var xhr = new XMLHttpRequest();

xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JS error logged');
} else if (xhr.status !== 200) {
console.error('Failed to log JS error.');
console.error(xhr);
console.error(xhr.status);
console.error(xhr.responseText);
}
};
xhr.send(JSON.stringify(error_data));

JSFiddle:

https://jsfiddle.net/nzfvm44d/

引用资料:

关于JavaScript 全局事件机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/951791/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com