浏览器常用监听事件

14次阅读

共计 842 个字符,预计需要花费 3 分钟才能阅读完成。

广告:Fundebug 错误监控插件,及时发现 Bug,提高 Debug 效率!
页面
// 初始化页面监听
document.addEventListener(“DOMContentLoaded”, ready);

// 页面跳转 hash
document.addEventListener(“hashchange”, navigation);
// 监听 pop 和 push 需要自定义
document.addEventListener(“popstate”, navigation);
document.addEventListener(“pushState”, navigation);

// 离开页面监听
document.addEventListener(“beforeunload”, leave);

自定义监听 popstate 和 pushState
history.pushState = this.resetHistory(“pushState”);
history.replaceState = this.resetHistory(“replaceState”);

resetHistory(type) {
let orig = history[type];
return function() {
let rv = orig.apply(this, arguments);
let e = new Event(type);
e.arguments = arguments;
window.dispatchEvent(e);
return rv;
};
}

error
window.onerror = function (errorMsg, url, lineNumber) {
alert(errorMsg + lineNumber);// 错误信息 +lineNumber
};

window.addEventListener(‘unhandledrejection’, event =>
{
console.log(‘unhandledrejection:’ + event);// 打印 event 查看所有报错信息
});

正文完
 0