在浏览器中处理后退/前进按钮单击

时间:2020-06-22 01:59:40

标签: javascript react-router browser-history html5-history history.js

  • 如果用户单击浏览器中的前进按钮,我要console.log(1)
  • -1 (如果用户单击“后退”按钮
  • ) 如果用户重新加载页面,
  • 0

到目前为止,这是我的代码,我无法获得-1,为什么我做错了?

我的方法是在组件的历史对象内设置状态,并将其与历史对象的长度进行比较...

async function handleBackForwardButton() {

    // If none, then zero
    const historyLength = Number(sessionStorage.getItem("historyLength"));
    let { state } = await window.history.state; 
    let position;
    if (state === null || state === undefined) {
      // New entry on the stack
      position = historyLength + 1;
      debugger;
      //  Stamp the entry with its own position in the stack
      window.history.replaceState(historyLength, /*no title*/ "");
      // (2) Keep track of the last position shown
      sessionStorage.setItem("historyLength", String(window.history.length));
      debugger;
      // (3) Discover the direction of travel by comparing the two
      const direction = Math.sign(position - historyLength);
      console.log("Forward should be (1) :" + direction);
      debugger;
      // forward should be (1)
    } else if (historyLength > state) {
      const direction = Math.sign(state - historyLength);
      console.log("Backward should be (-1) :" + direction);
      debugger;
      //One of backward (-1)
    } else if (historyLength === state) {
      const direction = Math.sign(state - historyLength);
      console.log("Reloading page should be (0) : " + direction);
      debugger;
      //Reloading page should be (0)
    }
  }

  window.addEventListener("pageshow", handleBackForwardButton);
  window.addEventListener("popstate", handleBackForwardButton); 

0 个答案:

没有答案