JavaScript captures window close events and uses javascriptwindow

Source: Internet
Author: User

JavaScript captures window close events and uses javascriptwindow

There is such a situation in the work. When the browser window is closed, the user is prompted for some operation.
When you close the window, you are prompted to save the current content. If you select Yes, the window is saved and closed. Otherwise, the window is not closed or saved.

I have found a lot on the Internet. I use js to handle window close events, either the onbeforeunload method or the onunload method.
It cannot be implemented. Then I suddenly thought of this method: use these two methods to achieve it together!

Cause:
The onbeforeunload event will be executed before closing the window. You can also decide whether to close the window. This method only requires the return value and is not "" or null; it will display a prompt window (ie and firefox have not been tried ).
Using this method alone cannot implement the above-mentioned prompts. Select "yes" and save the action.

If this parameter is not set to null, the returned value is a message indicating whether to close the window.
Onunload is executed after the window is closed, not before the window is closed. No matter what you do in this method, the last window will be closed.


Now we can combine these two methods to meet our needs. The first method prompts us, and the second method selects "yes" to save the data.


The sample code is provided here without refresh considerations.

 

Var isSave = false;
Function save (){
// Dosomething
}
Window. onbeforeunload = function (){

If (! IsSave ){
Return "the current data has not been saved. The close or refresh window will automatically save the data. Continue? ";
} Else {
Return "";
}
}
Window. onunload = function (){
If (! IsSave ){
Save ();
}
}

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.