浏览器经常使用监听事宜

广告: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检察一切报错信息
    });      
       
    原文作者:草丛迷了鹿
    原文地址: https://segmentfault.com/a/1190000018903163
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞