Domanda

I need to clear some session variables whenever user closes the browser window. The window can be closed in two ways:

  • the normal way by pressing the window close button
  • by pressing a custom button inside the window

I am using jQuery, so the listener is:

// clear some session variables
$(window).bind('beforeunload', function() {
    makeAjaxCall(some, params);
});

The window is closed by calling a function that eventually executes:

window.close();

The problem is that the second way to close the window only triggers the beforeunload event in FF. In Chrome the second way works only sometimes, in Safari it does not work at all. Any thoughts?


SOLUTION (so far):

// clear search filter whenever the user closes the window
$(window).on('beforeunload', function() {   // most browsers except Safari
    doSomeMagic(param);
    return;
}).on('unload', function() {         // Chrome
    doSomeMagic(param);
});

This works in most browsers: IE8+, Chrome, FF when closing window with window.close() and/or native browser button

It also works in Safari if window is closed by native browser window.

Does not work in Opera at all.

È stato utile?

Soluzione

Try this

$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){
     logout();

});

This solution works in all browsers and I have tested it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top