There are several posts online that show parts of dealing with the browser unload event.  Most of them are incomplete.  The trick is that if you return anything from the event handler then the browser leaving page dialog box will come up.  If you don’t want the dialog box to come up then return nothing.  For example,


//try... to detect browser/tab close
//if user clicks a link or submits a form we don't care here
var inFormOrLink = false;
$('a').each(function() {
 $(this).click(function(e) {
  inFormOrLink = true;
 })
});
$('form').each(function() {
 $(this).submit(function() {
  inFormOrLink = true;
 })
});
//return any value means prompt user to make sure they want to leave the page
$(window).bind("beforeunload", function() {
 //regular links are ok (regular dirty check will kick in)
 if (inFormOrLink) return;
 //if we get here user has done something to change url - Back, History, Close Browser
 //if something dirty on the page, make sure they want to leave
 var anyDirty = false;
 $('form').each(function() {
  if ($(this).are_dirty())
   anyDirty = true;
 });
 if (anyDirty) return "My App"; //IE puts the string in the dialog box, FF puts up their own message
 //otherwise bye, bye
 return;
});

The first two functions are trying to determine if the user just clicked on an anchor or hit submit on a form.  Both of these generate a unload page event, but that is ok since the user likely means to do this.

Then in the unload event handler we check if the user did click on something ‘legal’ in a form.  If so we are done.

Next we would like to check if the user has dirtied some data in a form on the page.  We are using a jQuery plugin for dirty checking so we poke around the forms and see if anything is dirtied.  If there is something of interest we want the leaving page dialog box to come up so we return the string we would like to see show up in the dialog.  As noted the browser really does whatever they want for the dialog box text that comes up.

If nothing is dirty we just return – do not return any value otherwise you get the dialog to show up.