监控js报错
window.addEventListener("error", (err) => {
console.log(err)
})
错误示例
window.addEventListener("error", (err) => {
console.log(err)
})
console.log(a);
image.png
监控js报错的同时监控资源加载失败,即加上捕获选项即可
window.addEventListener("error", (err) => {
console.log(err)
}, true)
错误示例
<link rel="stylesheet" href="err.css" />
<script>
window.addEventListener("error", (err) => {
console.log(err)
}, true)
console.log(a);
</script>
<img src="err.png" />
image.png
监听ajax请求
function _initListenAjax() {
let self = this;
function ajaxEventTrigger(event) {
console.log(event);
var ajaxEvent = new CustomEvent(event, {
detail: this
});
window.dispatchEvent(ajaxEvent);
}
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener('load', function ($event) {
ajaxEventTrigger.call(this, 'ajaxLoad');
}, false);
realXHR.addEventListener('timeout', function () {
ajaxEventTrigger.call(this, 'ajaxTimeout');
}, false);
realXHR.addEventListener('readystatechange', function () {
ajaxEventTrigger.call(this, 'ajaxReadyStateChange');
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
}
window.addEventListener("ajaxReadyStateChange", (err) => {
console.error("ajaxReadyStateChange")
console.log(err)
}, true)
_initListenAjax();
//步骤一:创建异步对象
var ajax = new XMLHttpRequest();
//步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端
ajax.open('get', 'http://www.xx.com/getStar.php?starName=' + name);
//步骤三:发送请求
ajax.send();
//步骤四:注册事件 onreadystatechange 状态改变就会调用
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
//步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
console.log(ajax.responseText); //输入相应的内容
}
}
监听未处理的promise
window.addEventListener('unhandledrejection', event => {
console.log(event.reason); // 打印"Hello, Fundebug!"
});
示例:
function foo() {
Promise.reject('Hello, Fundebug!');
}
foo();
网友评论