简体   繁体   English

如何使用 React js 检测浏览器标签关闭事件?

[英]How to detect browser tab close event with react js?

I am trying to detect browser tab / browser close event with react js to detect user log out action (call api).我正在尝试使用 react js 检测浏览器选项卡/浏览器关闭事件以检测用户注销操作(调用 api)。 I have tried using beforeunload event as我尝试使用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
    
    });
  });

It works fine if user closes the tab but the issue is it is also firing when user reload the page which I dont want for log out action, I've tried searching and tried these solutions as well but no work for me.如果用户关闭选项卡,它可以正常工作,但问题是当用户reload我不想进行注销操作的页面时它也会触发,我尝试搜索并尝试了这些解决方案,但对我没有用。 Are there any solutions to detect only when browser / browser tab closes and not reload?是否有任何解决方案可以仅在浏览器/浏览器选项卡关闭而不重新加载时进行检测?

Detect browser close event检测浏览器关闭事件

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

Warn user before leaving web page with unsaved changes在离开 web 页面之前警告用户未保存的更改

you missed to add the return function in your useEffect which runs the cleanup ie componentWillUnmount .您错过了在运行清理的useEffect中添加返回 function ,即componentWillUnmount

Your code will look something like this:您的代码将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM