JavaScript captures window Windows Close event

Source: Internet
Author: User

There is a situation in your work that prompts the user to do something when the browser window is closed.
Similarly, when the window is closed, prompt the user to save the current content, select Yes to save and close the window, select Do not close the window, do not save the operation.

Online find a lot, are said to use JS processing window closed event, either say onbeforeunload method, or say OnUnload method.
Feeling can not be realized. Then suddenly think of such a way: With these two methods together to achieve!

Reason:
The onbeforeunload event will be executed before the window is closed, and you can also decide whether to close the window , as long as it has a return value and is not "" or null; he will give a hint window (not to Ie,firefox).
This method alone does not implement the above-mentioned hint, select "Yes", and then do the save action.

and a non-null return value will be a hint of whether to close this window.
OnUnload is executed after closing the window, not before closing the window. No matter what you do in this method, the last window will be closed.


Now the two methods together, just to achieve our needs, the first method is prompted, the second method implementation of the choice is "yes" after the action: that is, save the data.


Here is an example code that does not consider the issue of refresh.

var issave =false;
function Save () {
//dosomething
}
Window.onbeforeunload =function () {

if(!Issave) {
return "the current data is not saved, and the Close or Refresh window automaticallySave Data, do you want to continue?";
}Else{
return "";
}
}
Window.onunload =function () {
if(!Issave) {
Save ();
}
}

JavaScript captures window Windows Close event

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.