I might have it even way easier than you
var isClose = false;
document.onkeydown = checkKeycode
window.onbeforeunload = doUnload;
function checkKeycode(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if(keycode == 116)
{
isClose = true;
}
}
function somefunction()
{
isClose = true;
}
function doUnload()
{
if(!isClose)
{
window.location = "LogOut.aspx"
}
}
Just add on the body tag
onmousedown="somefunction()"
This will launch the "LogOut.aspx" page whenever the window or the tab is closed, then you can have there that server side code you need. If you need to pass some data to the page, use the Session variable to handle the data.
Now, if you have many pages, and you need to launch that function from either page is opened, you i'll need to post this code in each page, reason why i suggest using a master page, and only put this code there