How to keep websocket connection open when page is refreshed?


#1

Is it possible to keep websocket connection open when page refreshed? What is the best way to know that user has not closed the browser just refreshed.
Thank you


#2

There is no way to do that, this is how browsers works. What exactly you are trying to achieve?


#3

Thank you so much sir.

I am trying to get a way using which I can update database if user socket is disconnected.

Here is the thing…

  1. User refresh so server and onClose event get fired and I make database query
  2. As soon as user page is reloaded, I make again a new query to the database since user has not left the site.

So, this makes unnecessary database calls and other codes executions.

So, I am just wondering if it is possible to to fire onClose event only when user close the browser and not the refresh…

I hope you got the point.

Many thanks again :slight_smile:


#4

As I said, that’s how browsers work. As soon as page is refreshed all connections are closed and their is no way around that.

What you can do here is defer the database queries on your server. I can explain how it should look like in theory.

  1. Create a class to track close connection requests.
  2. Everytime onClose is called, tell this class to execute the database query.
  3. The database query by this class isn’t executed right away, instead it is scheduled to be executed at 1min or whatever time makes sense.
  4. When you receive join event again, you ask this class to cancel the database query for that user.