A robust way to prevent window from unloading with onbeforeunload and addEventListener beforeunload

It’s annoying that sometimes the beforeunload event listener doesn’t not work. so I’m going to take some time starting an experiment.

Tests

test which of the following js code can prevent window unload

  • event.preventDefault()
  • event.returnValue='xxx'
  • return 'xxx'

scene1: in the “beforeunload” event listener

window.addEventListener('beforeunload', function(event){
  let message='Some changes are not saved yet!';
  // event.preventDefault();
  event.returnValue = message;
  // return message;
});

scene 2: in the onbeforeunload event handler

window.onbeforeunload=function(event){
  let message='Some changes are not saved yet!';
  // event.preventDefault();
  event.returnValue = message;
  // return message;
};

Reports

approaches to prevent window unload when usingwindow.addEventListener('beforeunload', listener)

UA \ effective? \ JS event.preventDefault() event.returnValue='xxx' return 'xxx'
IE 11 Y Y Y
Chrome 83 N Y N
Edge 18 Y Y N
Firefox 68 Y Y N
Safari 13

approaches to prevent window unload when using window.onbeforeunload=handler

UA \ effective? \ JS event.preventDefault() event.returnValue='xxx' return 'xxx'
IE 11 Y Y Y
Chrome 83 N Y Y
Edge 18 Y Y Y
Firefox 68 Y Y Y
Safari 13

Note:

  1. No macOS here thus Safari 13 cannot be test now, maybe later
  2. If you use jQuery(window).on('beforeunload', ...), result may be different from native addEventListener

Conclusion

Personally I think

  • event.preventDefault() will the future standard
  • event.returnValue='xxx' is most compatible now
  • return 'xxx'; is an issue left over by history

so I prefer using both event.preventDefault() and event.returnValue='xxx' to prevent page unloading.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章