Introduction
When making text edits or other changes on a webpage and attempting to navigate away from the page, browsers can display a confirmation prompt asking the user to confirm their navigation. This feature is useful for preventing users from accidentally losing unsaved changes.
Enabling the Prompt
To enable this navigation confirmation prompt in legacy browsers (IE6-8, Firefox prior to version 4), assign the window.onbeforeunload property a function reference:
Disabling the Prompt
To disable the navigation confirmation prompt, remove the function reference from window.onbeforeunload:
Checking for Unsaved Changes
The user's confirmation is triggered regardless of whether there are unsaved changes on the page. To check for unsaved changes, you can utilize your preferred validation framework or a custom solution.
For example, using jQuery, you could bind a change event to form fields to set window.onbeforeunload when a field contains a non-empty value:
Note:
In modern browsers, displaying a custom navigation confirmation message is considered a security hazard and has been removed. Browsers now only display generic messages. To enable or disable the navigation prompt in modern browsers, simply set or remove window.onbeforeunload to a function reference without a return value.
The above is the detailed content of How to Implement a 'Leave Page?' Confirmation Prompt in Legacy Browsers?. For more information, please follow other related articles on the PHP Chinese website!