Onbeforeunload is also called when the page is refreshed or closed. Onbeforeunload is called when going to the server to read a new page, but it has not yet started reading; while onunload has read the new page that needs to be loaded from the server and is about to replace it. Called when the current page is deleted. Onunload cannot prevent the page from being updated and closed. And Onbeforeunload can do it. I once built an exam system that involved preventing users from exiting the exam midway (intentionally or unintentionally). The code is as follows:
<script> <br>function checkLeave(){ <br>event.returnValue="Are you sure you want to give up the exam? ( The exam will be invalidated and the results will not be recorded)"; <br>} <br></script>
This allows the user to confirm whether they want to exit the exam room. In fact, BLOGJAVA will not When saving and jumping to other pages, there will also be a confirmation prompt (to prevent misoperation), and Onbeforeunload is also used.
It can also be used to close the session when the page is closed. The code is as follows (note: use window.screenLeft > 10000 to distinguish between close and refresh operations):
<script> <br>function closeSession (){ <br>//Close (do not close Session when refreshing) <br>if(window.screenLeft>10000){ <br>//Close Session (AJAX can be used) <br>} <br>} <br></script>