Setting onbeforeunload on body element in Chrome and IE using jQuery

Graeme picture Graeme · Nov 26, 2009 · Viewed 43k times · Source

I have a system where I want to check with the user if they're sure they want to leave the page once a dirty flag is set.

I'm using the following code - In FireFox, I can look at the page source through FireBug and the tag correctly has the onbeforeunload attribute inserted in it.

In Chrome and FireFox, this doesn't happen though and I'm able to navigate away from the page without any warning at all. The jQuery line to update the body tag is definitely being executed, it just isn't performing it.

if ($("body").attr('onbeforeunload') == null) {
    if (window.event) {
        // IE and Chrome use this
        $("body").attr('onbeforeunload', 'CatchLeavePage(event)');
    }
    else {
        // Firefox uses this
        $("body").attr('onbeforeunload', 'return false;CatchLeavePage(event)');
    }
}

Any ideas how to proceed from here?

Answer

krcko picture krcko · Nov 26, 2009

you cannot abort page unload by returning false. you must return string that will be shown to user in a message box, and he decides if he want to leave or stay on the page (by selecting either 'OK' or 'Cancel' button), so you need to write your code like this:

 window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
 };