Webpage lifecycle and socket.io client disconnection

The socket.io version I am using is 4.0.

I need to find out if a user has closed the browser / tab or just navigated away to another tab / another program / switched the front end device to standby. In other words I need to differentiate if the socket.io client is in idle mode or really closed. If the socket disconnects the reason for the disconnect event is always “transport close” independendent of the reason of the disconnect.

I have seen that the socket client is using the offline event internally. I had the idea to use the onbeforeunload event to set a flag in case the user is about to close the tab. But it seems that this event is quite unreliable and the behavior differs between the browsers/devices.