I want to capture the browser window/tab close event. I have tried the following with jQuery:
jQuery(window).bind(
"beforeunload",
function() {
return confirm("Do you really want to close?")
}
)
But it works on form submission as well, which is not what I want. I want an event that triggers only when the user closes the window.
If your form submission takes them to another page (as I assume it does, hence the triggering of
beforeunload
), you could try to change your form submission to an ajax call. This way, they won't leave your page when they submit the form and you can use yourbeforeunload
binding code as you wish.For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider using the following code, which is a slightly tweaked version of Slaks' code:
Note that since Firefox 4, the message "Do you really want to close?" is not displayed. FF just displays a generic message. See note in https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
The
beforeunload
event fires whenever the user leaves your page for any reason.For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
For jQuery versions older than 1.7, try this:
The
live
method doesn't work with thesubmit
event, so if you add a new form, you'll need to bind the handler to it as well.Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the
submit
andclick
events, and checking if thebeforeunload
happens more than a couple of seconds later.Maybe just unbind the
beforeunload
event handler within the form'ssubmit
event handler: