瀏覽器經常使用監聽事件

廣告:Fundebug錯誤監控插件,及時發現Bug,提升Debug效率!app

頁面

//初始化頁面監聽
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查看全部報錯信息
    });
相關文章
相關標籤/搜索