【问题标题】:Detect when browser back button is pressed - ReactJS检测何时按下浏览器后退按钮 - ReactJS
【发布时间】:2021-07-26 02:24:29
【问题描述】:

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

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

期待答案。提前致谢。

【问题讨论】:

  • 你到底想做什么?你要回到你自己网站上的某个地方吗?您实际上可以在这里做的事情并不多。
  • 当前后退按钮将我带到上一个窗口,我想在我的网站上做点什么。
  • 那将是一个巨大的安全风险。你将无法做到这一点。

标签: javascript reactjs web browser


【解决方案1】:

将这两行添加到您的 componentDidMount() 中。这对我有用

window.history.pushState(null, null, document.URL);
window.addEventListener('popstate', function(event) {
   window.location.replace(`YOUR URL`);
});

【讨论】:

  • 工作顺利!!!
【解决方案2】:

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

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?")}
})

【讨论】:

  • 应该在componentDidMount() 中吗?
  • 什么是componentDidMount?您可以将其粘贴到您的 js 文件中
  • componentDidMount 是一个反应生命周期方法。
【解决方案3】:

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

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);
  }

【讨论】:

  • 我尝试在componentDidMount 中添加它,但它不起作用 - window.addEventListener("popstate", () => { this.setState({ isBack: true }); alert("back!!!"); });
  • class BasicExampleClass extends Component { constructor() { super(); this.state = { isBack: false }; } componentDidMount() { window.addEventListener("popstate", () => { this.setState({ isBack: true }); alert("back!!!"); }); } } 我认为它工作正常。我已经更新了代码框:codesandbox.io/s/cranky-borg-5qwl3?file=/src/index.js
  • 这可以在 Chrome 中使用吗?我试过了,好像不行。
  • 是的,我在 Chromium 90.0.4430.93 上测试过
猜你喜欢
  • 1970-01-01
  • 2012-05-01
  • 2018-11-28
  • 1970-01-01
  • 2016-03-15
  • 2014-11-06
相关资源
最近更新 更多