views:

5342

answers:

5

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.

+1  A: 

Perhaps you could handle OnSubmit and set a flag that you later check in your OnBeforeUnload handler.

jeffamaphone
+7  A: 

Maybe just unbind the beforeunload event handler within the form's submit event handler:

jQuery('form').submit(function() {
    jQuery(window).unbind("beforeunload");
    ...
});
karim79
+4  A: 

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:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

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

The live method doesn't work with the submit 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 and click events, and checking if the beforeunload happens more than a couple of seconds later.

SLaks
wow! this works gr8
nik
A: 

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 your beforeunload binding code as you wish.

idrumgood
A: 

the given solutions are working. But what if a user refresh/reload the page and click on back and forward buttons of the browser then also the function going to fire

SKodukula