Dimitri
Dimitri

Reputation: 1966

Browser Window close detection

This is something that's been driving me nuts.

I'm trying to detect whether the uses closes or navigates away from a page in order to do an ajax response upon the event. I have tried almost every possible method to invoke this but no luck. The only thing I can think of is that the activate window in question was fired using: window.open() method. Could that cause any issues? What I have so far:

window.onbeforeunload = function() {
   //ajax stuff here
};

However, I've noticed that this does not work after the page is fully loaded. The event fires within the first few milliseconds (if I open the window and try to close it right away) during the page load and won't work after that.

Any ideas?

Upvotes: 1

Views: 838

Answers (2)

DarkAjax
DarkAjax

Reputation: 16223

I once ran into this issue, and found it worked for me only by setting async : false on the ajax, like this:

jQuery(window).bind('beforeunload', function () {
    jQuery.ajax({
        url: 'your.url',
        async: false,
        data: yourdata
        timeout: 2000 // or whatever timeout in milliseconds you want
        success: function(data){
            // Do whatever you want
        }
    });
});

As Ian mentioned on the comments, it's a good idea to set a timeout to prevent the window for taking too long to close in case the request takes a while. And keep in mind it won't work in all browsers...

Upvotes: 1

David Fariña
David Fariña

Reputation: 1604

This also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Upvotes: 1

Related Questions