JS 监听点击浏览器的前进按钮后退按钮

37 min read

监听时机

  • 点击浏览器的前进按钮/后退按钮
  • 执行js代码:history.go(n) / history.forward() / history.back()

语法

window.onpopstate = funcRef;

场景

用于浏览器导航监听,获取导航的相关信息

const getStateFromLocation = () => {
  const { pathname, search, hash } = window.location;
  const urlParams = new URLSearchParams(search);
  const state: State = {
    pathname: getValidPathname(pathname),
    hash: hash,
    query: {},
  };

  if (search !== "") {
    state.query = {};
    state.query.tag = urlParams.get("tag") ?? undefined;
    state.query.type = (urlParams.get("type") as MemoSpecType) ?? undefined;
    state.query.text = urlParams.get("text") ?? undefined;
    state.query.shortcutId = Number(urlParams.get("shortcutId")) ?? undefined;
    const from = parseInt(urlParams.get("from") ?? "0");
    const to = parseInt(urlParams.get("to") ?? "0");
    if (to > from && to !== 0) {
      state.query.duration = {
        from,
        to,
      };
    }
  }

  return state;
};

注意

不会监听pushState , replaceState 事件

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // 弹出 "location: http://example.com/example.html, state: null
history.go(2);  // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}