简体   繁体   中英

Correct way to handle close vs refresh tab in the browser

i have a web chat application made with NextJS, and i wanna kick the user from chat when close tab, but none action when user refresh tab. How can I achieve this? Have to be a solution for mobile too.

If you have a chat app, you're almost certainly using websockets. Kick the user from chat (say) a minute after their socket closes if they have no other active sockets.

On the server, monitor the opening and closing of websockets for each user. When a user opens a websocket, associate that socket with the user in the server's memory. When a user closes a websocket (which could be a result of either the user closing the page/browser, or refreshing their page), check if they have any other active sockets. If not, set a timeout for, say, a minute from now. When that minute is up, check if the user still has no active sockets. If not, then they haven't refreshed the page; they've closed it completely, so kick them. If so, then they've reconnected and shouldn't be kicked.

Also clear the timeout associated with the user any time that user connects a new websocket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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