My guess - you cannot.
I mean, your code will not be able to say, is this guy goes to another page, or closes hte window.
You should use reasonable value for session timeout in server settings.
You actually could try to use "onbeforeunload" to set some flag on a server side, and then if it is not reset in some amount of time, invalidate session, and all your pages will have hidden frame, and they will load into it some
jsp for their "onload" event, and this jsp will reset this flag. So, page got "onbeforeunload", it set flag in a session, another page loads - it loads this hidden frame, wich reset value in a session.
But it doesn not sounds good even for me