0

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

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Oscar
  • 13
  • 1
  • Refer this duplicate - https://stackoverflow.com/questions/11453741/javascript-beforeunload-detect-refresh-versus-close – Ananda Prasad Bandaru Aug 30 '22 at 02:02
  • Does this answer your question? [javascript beforeunload detect refresh versus close](https://stackoverflow.com/questions/11453741/javascript-beforeunload-detect-refresh-versus-close) – Stephen Ostermiller Aug 30 '22 at 17:24

1 Answers1

1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320