Home > Software design >  Correct way to handle close vs refresh tab in the browser
Correct way to handle close vs refresh tab in the browser

Time:08-30

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.

CodePudding user response:

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.

  • Related