there seems to be a lot of confusion about how to manage page exit, and this question doesn’t seem to get any less frequent on the boards.

window.onunload is probably not what you want. it serves pretty much solely as an opportunity to do cleanup – you can’t prevent a page exit using this method, or perform any substantive actions, as it’ll fire as the page is closing.

window.onbeforeunload is most likely what you’re looking for to manage page exit, and since it can affect browser behavior, it’s use is restricted with good reason.

basically, if the handler assigned to this event returns any value, that value will appear in a modal dialog whenever a user tries to leave the page (either by clicking a link, refershing, hitting the back button, etc). beneath that message, the dialog will provide 2 buttons, which cannot be edited or managed in any way – one button will allow the user to leave the page, the other will ‘cancel’ the page exit (the exact verbiage of each button’s label varies between browsers).

most documentation states that if any string values is returned, this prompt will fire – some browsers will attempt to convert any return value to a string, however, so it’s best to not return anything at all if you don’t want to force the dialog.


one might expect the above to work fine – but in some browsers, the dialog will show the message “true” above the buttons (since the function actually did provide a return). Changing “true” to “false” doesn’t remedy this, and the user will still be presented with the exit dialog.

just omit the return entirely to skip the prompt.

so with the above example, if someCondition doesn’t equal someValue, the user will be shown the exit dialog when attempting to leave the page. if someCondition does equal someValue, no prompt will appear and the user will exit the page normally.

also to note – IE (some flavors? I haven’t tested…) likes to have the window.event.returnValue set to the return value of the function, like so:

finally, i’ve heard (but haven’t experienced first-hand) that a lot of library (jQuery, prototype, mootools, etc) handle this event inconsistently, and it’s usually best to assign it directly to the window event handler directly.