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

前端 未结 5 1370
眼角桃花
眼角桃花 2020-12-11 16:46

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 bac         


        
相关标签:
5条回答
  • 2020-12-11 17:06
    $(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.

    0 讨论(0)
  • 2020-12-11 17:06

    You could also consider not setting the window.beforeunload event untill your list of conditions are met.

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

    Then just call that method on certain events that might change the outcome of your 'conditions are met'.

    0 讨论(0)
  • 2020-12-11 17:12

    Condition for back-end

    var confirmExist = function (e) {
        return true;
    }
    window.onbeforeunload = confirmExist;
    http get, post request
    .then(function(r)) {
        window.onbeforeunload = null;
    }
    
    0 讨论(0)
  • 2020-12-11 17:21

    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?";
    }
    
    0 讨论(0)
  • 2020-12-11 17:24

    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.

    0 讨论(0)
提交回复
热议问题