How can I prevent onbeforeunload from firing when a certain condition is met?

I have a page on which I want to confirm whether the user wants to leave. I have to confirm only when a certain condition is met, so I wrote code like this

var back=false;
back=//check if user pressed back button
window.onbeforeunload = function (e) {
    alert(back);   //this alerts true
    if(back==true)
        return false;
        //e.preventDefault;   --this does not work too
};

but it does not work. I mean, when I press the back button, it should always work, and I still get a confirmation message even when I return false. What can be wrong? thank

+8
source share
5 answers

Returns a string if you want to give the user the ability to abort the upload. Do not return anything 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?";
}
+13
source
$(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');
});

. .

+2

window.beforeunload , .

var confirmUserToLeave = function () {
    if (/* conditions are met */) {
        window.unbeforeunload = function (e) {
            /* whatever you want to do here */
        };
    } else {
        window.unbeforeunload = undefined;
    }
};

, .

0

back-end

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

:

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

, window.addEventListener() beforeunload onbeforeunload.

The reason your originally published code didn't work is because it falseis a nonzero value. If you returned nullor undefinedin a situation where you do not want to create a pop-up warning, your code would work as expected.

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

0
source

All Articles