enhanceAppFile.js 1.1 KB
Newer Older
璃白.'s avatar
璃白. 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
class SidebarRedirect {
  menuList = [];
  constructor() {
    this.init();
  }
  init() {
    this.reWriteUrlFunction();
    window.addEventListener("pushState", e => {
      setTimeout(() => {
        const list = this.getMenuList();
        this.redirect(list);
      });
    });
    window.onload = () => {
      const list = this.getMenuList();
      this.redirect(list);
    };
  }
  getMenuList() {
    const menuList = [...document.querySelectorAll(".sidebar .sidebar-link")];
    return menuList;
  }
  redirect(list) {
    const len = list.length;
    if (len === 1) {
      console.log(list[0]);
      location.replace(list[0].href);
    }
  }
  reWriteUrlFunction() {
    const _historyWrap = function (type) {
      const orig = history[type];
      const e = new Event(type);
      return function () {
        const rv = orig.apply(this, arguments);
        e.arguments = arguments;
        window.dispatchEvent(e);
        return rv;
      };
    };
    history.pushState = _historyWrap("pushState");
    history.replaceState = _historyWrap("replaceState");
  }
}

export default new SidebarRedirect();