When a user interacts with the site, set the last activity time.
If it is more than 30 minutes or so, you can assume that they are offline.
You can also explicitly disconnect someone offline when they log out.
However, your case is a little different. You can use the heartbeat script style.
While they are on the page, use setInterval() to extend the validity period to the maximum range (in case the user leaves his browser window for several hours in a row).
source share