The best you can do it to capture the event of someone leaving your page.
This will be fired by a browser going to a new page or closing the browser.
This can then call a specific url in which you can register the event on your server. I'm not sure all browsers will accept this event, and there is also a risk of the browser moving on if it takes to long.
Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
Another option, which probably works better, is that your javascript code "pings" your server every so often to confirm that the user is still on the page, you can then deduce that the user has left the page if no ping has been received after the ping interval has passed.
More info can also be found here: Capture event onclose browser
If I were to develop this I would go with pinging the server every 10-30 seconds and updating the user table with a "latest date the user was online" value.