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

前端 未结 5 1382
眼角桃花
眼角桃花 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: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.

提交回复
热议问题