Javascript Onunload and Onbeforeunload usage Summary

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.