【问题标题】:How to detect browser tab close event with react js?如何使用 React js 检测浏览器标签关闭事件?
【发布时间】:2020-12-22 10:27:09
【问题描述】:

我正在尝试使用 react js 检测浏览器选项卡/浏览器关闭事件以检测用户注销操作(调用 api)。我尝试使用beforeunload 事件作为

  useEffect(() => {
    window.addEventListener("beforeunload", function(e) {

      let confirmationMessage = "o/";

      (e || window.event).returnValue = confirmationMessage; //Gecko + IE

      console.log("logout !");
      return confirmationMessage; //Webkit, Safari, Chrome
    
    });
  });

如果用户关闭选项卡,它工作正常,但问题是当用户reload 我不想退出操作的页面时它也会触发,我尝试搜索并尝试了这些解决方案,但没有工作我。是否有任何解决方案可以仅在浏览器/浏览器选项卡关闭而不重新加载时进行检测?

Detect browser close event

https://stackoverflow.com/a/5593734/11866037

Warn user before leaving web page with unsaved changes

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您错过了在运行清理的useEffect 中添加返回函数,即componentWillUnmount

    您的代码将如下所示:

    useEffect(() => {
        return () => {
    
           window.addEventListener("beforeunload", function(e) {
    
          let confirmationMessage = "o/";
    
          (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    
          console.log("logout !");
          return confirmationMessage; //Webkit, Safari, Chrome
        
        });
       }
       
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多