lovesh lovesh - 4 months ago 25
Javascript Question

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

i have a page on which i want to confirm if 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
return false;
//e.preventDefault; --this does not work too

but this does not work. i mean when i click on back button this onbeforeunload still fires and i still get the confirmation message even when i m returning false.Whats can be wrong?


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?";