I want to track users that are online at the moment.
The definition of being online is when they are on the index page of the website which has the chat function.
In the general case, there's no way to know when a user leaves your page.
But you can do things behind the scenes such that they load something from your server frequently while they're on the page, eg. by loading an with some content that reloads every minute:
That will cause some small extra server load, but it will do what you want (if not to the second).