0

I have a system in which the page must not be closed/unloaded until a certain condition is met. This is to force staff to complete very important information.

I know it is NOT good UI practice, I totally agree but in this case after lengthy discussions it is 100% necessary.

I have tried the following code:

 $(window).bind('beforeunload', function (event) {
                cancelEvent(event);
                stopEvent(event);
 });

function cancelEvent(e) {
    if (!e) e = window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}

function stopEvent(e) {
    if (!e) e = window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
}

The above code does not work.

Is there anyway to kill the unload event and keep the page shown?

The targeted browsers are IE 7-9 so even if it doesn't work on modern browsers that would be fine.

Thanks again.

Lemex
  • 3,772
  • 14
  • 53
  • 87
  • See [jAndy's](http://stackoverflow.com/a/8743481/3095977) answer on the topic. –  May 05 '14 at 09:22

1 Answers1

2

It's not only poor UI design, it can't be done. What you can do in beforeunload is to return a string to the user, which will then be displayed in a prompt where user has to confirm navigation.

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

Your best option is to provide a harsh enough message, eg. "You are about to leave the page before process X has finished. Don't do this, you will ruin everything. Seriously click Cancel now."

David Hedlund
  • 128,221
  • 31
  • 203
  • 222