On some pages, users need to prompt the user before exiting whether the content of the current page has been saved to prevent data loss!
We can do this with the onbeforeunload event.
Trigger the "onbeforeunload" event when you close the window or press F5
Definition and Usage
The onbeforeunload event is triggered when it is about to leave the current page (refresh or close).
This event can be used to pop up a dialog box that prompts the user to continue browsing the page or leave the current page.
The default message for the dialog box differs depending on the browser, and the standard information is similar to "Are you sure you want to leave this page?" "。 This information cannot be deleted.
But you can customize some message prompts to appear in the dialog box along with the standard information.
Note: If you do not specify the onbeforeunload event on the <body> element, you need to add an event on the Window object and use the ReturnValue property to create the custom information (view the following syntax instance).
Note: In the Firefox browser, only the default reminder message (No custom information is displayed) is displayed.
method One:
<script type= "Text/javascript" > window.onbeforeunload = function () { return "confirm leaving the current page?" Unsaved data will be lost ";} </script>
Method Two:
<! DOCTYPE html>
Browser support Scenarios
The number in the table represents the version number of the first browser that supports the event.
Extended
Of course, if you just use the onbeforeunload event is not enough to meet the demand, because this processing in the submission of the form will also appear when the closure prompt, it is very unfriendly.
One solution is to cancel the event before the form is submitted.
The code is as follows:
<form method= "POST" action= "http://www.baidu.com" onsubmit= "return Destroy ()" ><input type= "Submit" value= " Submit " /></form> </body> <script type=" Text/javascript "> window.onbeforeunload = function () { return "Confirm leaving the current page?" Unsaved data will be lost ";} /*** Destroy reminder event before submitting form */function destroy () {window.onbeforeunload = null;} </script>
JavaScript off page reminders, frequently used to turn off reminders on edit pages