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

前端 未结 5 1372
眼角桃花
眼角桃花 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条回答
  •  -上瘾入骨i
    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'.

提交回复
热议问题