反应-检查选项卡或浏览器何时关闭,但不刷新 [英] React - check when tab or browser is closed, but not on refresh

查看:57
本文介绍了反应-检查选项卡或浏览器何时关闭,但不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我想在选项卡关闭或浏览器关闭时断开所有用户的连接.但是,当我刷新页面时,所有用户也都断开了连接,刷新时不应发生这种情况.是否可以避免在刷新时执行此事件?我看到一些用户在使用localStorage,但我仍然不明白这一点.

I want to disconnect all my users when the tab is closing or the browser is getting closed, so far so good. But when I refresh the page, all my users get disconnected too, this should not happen on refresh. Is it possible to avoid to execute this event on refresh? I saw some users doing with localStorage, but I still didn't get the point.

componentDidMount() {
  this.beforeUnloadListener();
}


beforeUnloadListener = () => {
  window.addEventListener("beforeunload", (ev) => {
    ev.preventDefault();
    // code to logout user
  });
};

推荐答案

在进行卸载之前,您无法区分是页面刷新还是浏览器关闭.beforeunload这是一个非常令人困惑的事件,请避免使用它.

The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.

因此,在处理会话的情况下,应使用会话存储.sessionStorage对象仅存储一个会话的数据(关闭浏览器选项卡时,该数据将被删除).

Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).

这篇关于反应-检查选项卡或浏览器何时关闭,但不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆