Onbeforeunload is also called when the page is refreshed or closed. Onbeforeunload is called when the server is about to read a new page. At this time, it has not started reading; onunload has read the new page to be loaded from the server and is called when the current page is to be replaced. Onunload cannot prevent page updates or closures. Onbeforeunload can be used. I used to take an examination system to prevent users from leaving the examination halfway (intentionally or unintentionally). The Code is as follows:
Copy codeThe Code is as follows:
<Body onbeforeunload = "checkLeave ()">
<Script>
Function checkLeave (){
Event. returnValue = "are you sure you want to cancel the test? (The exam is voided and no score is recorded )";
}
</Script>
In this way, you can determine whether to exit the test room. In fact, when you write a BLOG by using BLOGJAVA, if you do not save it and jump to other pages, a confirmation prompt will also be displayed (to prevent misoperation ), onbeforeunload is also used.
In addition, it can be used to close the session when the page is closed. The Code is as follows (Note: Use window. screenLeft> 10000 to differentiate the close and refresh operations ):
Copy codeThe Code is as follows:
<Body onbeforeunload = "closeSession ()">
<Script>
Function closeSession (){
// Close (do not close the Session when refreshing)
If (window. screenLeft & gt; 10000 ){
// Disable the Session operation (AJAX can be used)
}
}
</Script>