There is no way in JavaScript to determine the difference between a page change, the user clicking the back button (which is the same as a page change essentially), or the user clicking the close button. They are all 'unloading' the page. The browser does not send additional information to tell you what happened to cause the page to be unloaded. And, relying on this unload event to clear a session is not good practice. Other things may close the browser without triggering that event cleanly. This is a common problem people face with the page unload event in JavaScript. Generally you should not rely on it to manage server-side tasks.
Assuming you're using ASP.NET, the sessions will automatically time out based on the Session.Timeout value. Normally this is 30 minutes, but it can be changed depending settings:
Session timeout in ASP.NET
If you want to tie a server-side event with C# code to a Session-End event, you can do so by putting an event handler in your global.aspx file. You do not need to rely on JavaScript. You do need to wait for the session to time out though. For example:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.sessionstatemodule.end?view=netframework-4.8
Further reading:
When is Session_End() called in ASP.NET MVC?
Code example from above that would go in your global.aspx.cs file:
protected void Session_End(object sender, EventArgs e)
{
//do whatever you need to here
System.Diagnostics.Debug.WriteLine("Session_End");
}