how can i prevent onbeforeunload from firing when a certain condition is met?

For the sake of completeness here a more modern, recommended approach:

let warn = false;
window.addEventListener('beforeunload', e => {
  if (!warn) return;
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
warn = true;  // during runtime you change warn to true

Typically, it is better to use window.addEventListener() and the beforeunload event, instead of onbeforeunload.

Source

The reason why your originally posted code didn't work is that false is a non-null value. If you would have returned null or undefined in the situation where you don't want to spawn a pop-up warning your code would have worked as expected.

The currently accepted answer works because JavaScript implicitly returns undefined at the end of the function.


Return a string if you want to offer an option to the user to abort the unload. Return nothing in other cases.

var back = false;
back = true; //Somewhere, the condition is set to true
window.onbeforeunload = function (e) {
    if(back == true)
        return "Are you sure to exit?";
}

$(window).bind('beforeunload',function() {
    return "'Are you sure you want to leave the page. All data will be lost!";
});

$('#a_exit').live('click',function() {
    $(window).unbind('beforeunload');
});

Try this. Above code is working in most of conditions.


Condition for back-end

var confirmExist = function (e) {
    return true;
}
window.onbeforeunload = confirmExist;
http get, post request
.then(function(r)) {
    window.onbeforeunload = null;
}

Tags:

Javascript