Solving this problem is no easy task, unfortunately. However, it is possible to find a solution. The following answer is a compilation of various responses from Stack Overflow.
Simple Component:
Recognizing when the window is being closed can be achieved by using the onunload
event handler.
Complex Component:
Distinguishing between a refresh, following a link, or closing the desired window can be challenging. Eliminating link follows and form submissions is relatively straightforward:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (!inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Simplistic Approach
Inspecting event.clientY
or event.clientX
to determine the action that caused the event to fire.
function doUnload(){
if (window.event.clientX < 0 && window.event.clientY < 0){
alert("Window closed");
}
else{
alert("Window refreshed");
}
}
Using Y-Axis isn't effective since it's negative for clicks on reload or close buttons but positive for keyboard shortcuts. X-Axis variations across browsers also pose challenges. Implementing a series of conditions based on event coordinates is not entirely reliable.
Advanced Strategy
(Attributed to Julien Kronegg) Leveraging HTML5's local storage and AJAX communication between client and server. Note: This method depends on browser support for HTML5 local storage.
Add an onunload
handler to the window as shown below:
function myUnload(event) {
if (window.localStorage) {
window.localStorage['myUnloadEventFlag'] = new Date().getTime();
}
askServerToDisconnectUserInAFewSeconds();
}
And include an onload
handler on the body:
function myLoad(event) {
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)) t0 = 0;
var t1 = new Date().getTime();
var duration = t1 - t0;
if (duration < 10 * 1000) {
askServerToCancelDisconnectionRequest();
} else {
// handle tab/window close event
}
}
}
On the server side, manage disconnection requests and implement a timer thread to disconnect users after a specified time. Canceling a disconnection request removes it from the list, preventing user disconnection. This approach can also differentiate between tab/window closings and other actions like link follows or form submissions.
Final Thoughts:
If the objective is to clear cookies upon window closure to prevent their use in future sessions, the mentioned approach is suitable. By invalidating the cookie on the server once the client is disconnected, you can detect old session cookies during subsequent login attempts, enabling deletion and, if needed, issuance of new cookies.