Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
    if(back==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? Thanks

like image 837
lovesh Avatar asked Oct 21 '11 09:10

lovesh


2 Answers

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?";
}
like image 63
Rob W Avatar answered Oct 06 '22 01:10

Rob W


$(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.

like image 34
Niko Jojo Avatar answered Oct 05 '22 23:10

Niko Jojo