AJAX and user leaving a page

前端 未结 4 1709
心在旅途
心在旅途 2021-02-04 05:48

I\'m working on a chat and I\'m trying to figure out how I can detect that the user has left the page or not. Almost everything is being handled by the database to avoid the fro

4条回答
  •  天命终不由人
    2021-02-04 06:29

    This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. Instead of this, what you can do is.

    1. Try connecting a socket so that you can know the user is disconnected when the socket is disconnected
    2. You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. If you didn't receive the request - even after 2 secconds - disconnect the user.

提交回复
热议问题