JavaScript capture window close event
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 ();
}
}