Detect Close windows event by jQuery

Duc Le picture Duc Le · May 23, 2013 · Viewed 129.3k times · Source

Could you please give me the best way to detect only window close event for all browsers by jQuery?

I mean clicking X button on the browser or window.close(), not meaning F5, form submission, window.location or link. I was looking for many threads but have not found the right way yet.

Answer

mjimcua picture mjimcua · May 23, 2013

You can use:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})

Source Browser window close event