Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting onbeforeunload on body element in Chrome and IE using jQuery

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?

like image 416
Graeme Avatar asked Nov 26 '09 10:11

Graeme


2 Answers

It's not pretty, but it did the trick.

var warnclose = true;
var warn = function(e) {
    var warning = 'Your warning message.';
    if (warnclose) {
        // Disables multiple calls
        warnclose = false;

        // In case we still need warn to be called again 
        setTimeout(function(){
            warnclose = true;
        }, 500);

        return warning;
    }
};
window.onbeforeunload = warn;
like image 95
Akin Williams Avatar answered Sep 23 '22 01:09

Akin Williams


try this

  <script type=\"text/javascript\">
        var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
        var leave_message = 'You sure you want to leave?'
        function goodbye(e) 
        {
            if(dont_confirm_leave!==1)
            {
                if(!e) e = window.event;
                //e.cancelBubble is supported by IE - this will kill the bubbling process.
                e.cancelBubble = true;
                e.returnValue = leave_message;
                //e.stopPropagation works in Firefox.
                if (e.stopPropagation) 
                {
                    e.stopPropagation();
                    e.preventDefault();
                }

                //return works for Chrome and Safari
                return leave_message;
            }
        }   
    window.onbeforeunload=goodbye;
    </script>
like image 28
Youri Arkesteijn Avatar answered Sep 24 '22 01:09

Youri Arkesteijn