How to Use js onbeforeunload and onunload events

Source: Internet
Author: User

Onbeforeunload and onunload events are the functions of the two functions before and when the page is loaded, which can prevent prompt refresh when the page is refreshed or when the page is closed, next I will introduce the usage of onbeforeunload and onunload events.

During the development of various projects, we often use the onbeforeunload event, which can avoid user operation errors and give users a chance to choose, for example, we often use the editor. If you choose to leave, the onunload or onbeforeunload event will naturally be triggered. But if you choose to cancel, how can we detect it?

Assume that a page exit cancellation event is called onunloadcancel. Obviously, this event should be triggered after the user presses the cancel button in the dialog box. However, it is not that simple to close the trigger process of the prompt dialog box. Let's first review this process:

The Code is as follows: Copy code

Window. onbeforeunload = function () {return "really leave? ";}

The onbeforeunload event is triggered when the user is about to leave the page (such as pressing the close button or refreshing the page. Our script cannot determine whether to block page closure in this event. The only thing that can be done is to return a string, which is only used as the description text in the close selection dialog box, you can choose to disable it or not. But we have no idea which one to choose.

However, if you carefully analyze the problem, it is actually not the case. If the user chooses to close the page, all the subsequent running code will be byebye. If the user stays on the page, nothing will happen, except the onbeforeunload event. Therefore, we can do some tricks in the onbeforeunload event to register a timer that will be started several milliseconds later. If the page is actually closed, the timer will certainly be voided; the page is still there, and the latency of several milliseconds is no error for this originally asynchronous interface interaction event.

The Code is as follows: Copy code

Window. onbeforeunload = function (){
SetTimeout (onunloadcancel, 10 );
Return "are you sure you want to leave? ";
}
Window. onunloadcancel = function (){
Alert ("cancel leaving ");
}

We use setTimeout to execute onunloadcancel with a latency of 10 ms. If the page is closed, the timer will be destroyed. Otherwise, the timer will continue. However, during the test, we found that FireFox has two bugs:

1) Sometimes, when you press the close button, onunloadcancel will be executed and a dialog box will pop up. If it is changed to while (1), the browser will remain stuck. This indicates that onunloadcancel is indeed executed, but the interface is destroyed, but the script is not paused.
2) If you exit by refreshing the page, only onbeforeunload is executed once, but you click the X button to close the page, onbeforeunload will be executed twice. Therefore, we still need to improve to be compatible with FF.

The Code is as follows: Copy code

Var _ t;
Window. onbeforeunload = function (){
SetTimeout (function () {_ t = setTimeout (onunloadcancel, 0)}, 0 );
Return "are you sure you want to leave? ";
}
Window. onunloadcancel = function (){
ClearTimeout (_ t );
Alert ("cancel leaving ");
}

Here I used a method that I could not tell the cause. It should be regarded as hack and solved the bug in FF.

Let's take a look at how the csdn code is written: (catch it directly, it is also a good way)

The Code is as follows: Copy code

ShowConfirm = true;
Window. onbeforeunload = function (){
If (showConfirm ){
If (csdn. val2 ("editor"). replace (/<. +?> /G, ""). length> 0) {// can be ignored
Try {return "your article has not been saved! ";} Catch (err ){}
}
}
};

Example:

The Code is as follows: Copy code

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> onunload test </title>
<Script>
Function checkLeave (){
Alert ("welcome to come back next time! ");
}
</Script>
</Head>
<Body onunload = "checkLeave ()">
</Body>
</Html>

A good way to determine whether the page is actually closed and refreshed:

 

The Code is as follows: Copy code
Window. onbeforeunload = function (){
Alert ("= onbeforeunload = ");
If (event. clientX> document. body. clientWidth & event. clientY <0 | event. altKey ){
Alert ("you disabled the browser ");
} Else {
Alert ("You are refreshing the page ");
}
}

If the page is forcibly closed, the pop-up window prompts: Are you sure you want to leave ?, Click OK to save the data and exit. Click Cancel to stay on the current page.

Only Internet Explorer is supported.

The Code is as follows: Copy code

Document. body. onbeforeunload = function (){
Event. returnValue = "";
}

Document. body. onunload = function (){
}

Related Article

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.