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

It’s annoying that sometimes the beforeunload event listener doesn’t 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 thus Safari 13 cannot be tested 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.

你可能感兴趣的:(Front-end,beforeunload,preventDefault,cross-browser)