Dialog box runs for 1 sec and disappears?

beforeunload utilizes a method built in to the browser, you need to return a string to it, and the browser will display the string and ask the user if they want to leave the page.

You cannot use your own dialog boxes (or jQueryUI modal dialogs) to override beforeunload.

beforeunload cannot redirect the user to another page.

$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will make an alert box pop up that says 'Are you sure you want to leave?' and asks the user if they wanna leave the page.

(UPDATE: Firefox doesn’t display your custom message, it only displays its own.)

If you want to run a function as the page is unloading, you can use $(window).unload(), just note that it can’t stop the page from unloading or redirect the user. (UPDATE: Chrome and Firefox block alerts in unload.)

$(window).unload(function(){
  alert('Bye.');
});

Demo: http://jsfiddle.net/3kvAC/241/

UPDATE:

$(...).unload(...) is deprecated since jQuery v1.8, instead use:

$(window).on('unload', function(){
});

Leave a Comment