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:
- No macOS here thus Safari 13 cannot be test now, maybe later
- If you use
jQuery(window).on('beforeunload', ...)
, result may be different from native addEventListener
Conclusion
Personally I think
event.preventDefault()
will the future standardevent.returnValue='xxx'
is most compatible nowreturn 'xxx';
is an issue left over by history
so I prefer using both event.preventDefault()
and event.returnValue='xxx'
to prevent page unloading.