I have a basic Socket.io implementation using NodeJS with Express server. (Basically the Get Started example on Socket.io web site)
On desktop it connects/disconnects as expected. When you browse to the page the socket connects. Connection events are fired both on the client and server side. And she the user closes the browser, the socket disconnects.
But on mobile the disconnect does not work as expected. When you browse to the page the socket connects, and events are fired. But the socket.io does not disconnect if the user
- closes the browser app (Safari or Android browser) (pressing the home button)
- switches to another app
- opens a new tab
- puts the device to sleep (pressing the sleep button)
And the disconnect event is not fired on the server nor the client.
I tried to detect those events via JavaScript using window.pagehide but it is also not firing properly.
Does any one have any idea how to make sure the Socket.io disconnects when the user walks away from the page on mobile.
Any help much appreciated. Doruk
So as far as I know there is no 'event' that happens on mobile browser to say, "hey I am not viewing you anymore".
One way you could try and do this though is to have a heartbeat on your webpage and trigger a client-side store whenever an event happens.
Let's say I make a chat app, I would have on every message to update my store with my latest activity time.
Or a webpage, and for a route getting clicked I update my store to save the time of that activity.
Then I would have something either on server or client that did some kind of a heartbeat.
If you did the server have it ping the clients however often you want and see what their last activity was, if it had been longer than 10 minutes, disconnect. Then you could open a modal asking something like "Would you like to reconnect?" When they click yes you re-initiate the socket.
Or:
You could put it on the client, and just have an interval check every 30 seconds to see if that store had been last activated if it was longer than 10 minutes, disconnect the socket and flag the modal message "would you like to reconnect?".
You could also fire a reconnect event on new page loads or messages being entered and skip the modal altogether to make it more seamless.
After some research I found a nice JS library detecting if the page is still visible; if the user walks away; or even if the page is idle for a certain period.
The library is ifvisible.js (https://github.com/serkanyersen/ifvisible.js/)
It detects the following
They all work on both iOS and Android, with an exception of the last item on Android. On some older Android devices this event is not detected. I am using an long idle timeout instead.
So with the help of these events I disconnect the socket manually.