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
1 2 3 4 5 6 | 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
1 2 3 4 5 6 | 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 with “beforeunload” event listener
| UA \ effective? \ JS | |||
|---|---|---|---|
| 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 with onbeforeunload event handler
| UA \ effective? \ JS | |||
|---|---|---|---|
| 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 and Safari 13 cannot be test now, maybe later
Conclusion:
Personally I think
event.preventDefault() will the future standard toevent.returnValue='xxx' is most compatible nowreturn 'xxx'; is an issue left over by history
so I prefer using both