检测何时按下浏览器后退按钮 - ReactJS

时间:2021-05-03 17:02:19

标签: javascript reactjs web browser

如何检测浏览器(Chrome、FireFox、Safari 等)上的后退按钮何时通过我的 React 网站上的 JavaScript 被点击并采取相应措施?

此外,当按下移动设备上的后退按钮时,事件是否与点击浏览器中的后退按钮时相同或相似?

期待答案。提前致谢。

2 个答案:

答案 0 :(得分:0)

这在某些时候有效,但目前还没有可靠的方法来检测这样的东西。

window.addEventListener("beforeunload",function(){
//Checking if the user hasn't clicked on something on the page
if(document.activeElement==document.querySelector("body")){console.log("Back Button Maybe?")}
})

答案 1 :(得分:0)

这是一个非常简单的自定义钩子:

const useBackButton = () => {
  const [isBack, setIsBack] = useState(false);
  const handleEvent = () => {
    setIsBack(true);
  };

  useEffect(() => {
    window.addEventListener("popstate", handleEvent);
    return () => window.removeEventListener("popstate", handleEvent);
  });

  return isBack;
};

工作示例:https://codesandbox.io/s/cranky-borg-5qwl3?file=/src/index.js

客观方法:

  constructor() {
    super();
    this.state = {
      isBack: false
    };
    this.onPopstate = this.onPopstate.bind(this)
  }

  onPopstate() {
    this.setState({ isBack: true });
    alert("back!!!");
  }

  componentDidMount() {
    window.addEventListener("popstate", this.onPopstate);
  }

  componentWillUnmount() {
    window.removeEventListener("popstate", this.onPopstate, false);
  }