When modifying data on a web page, it's common to want to prevent users from navigating away without saving their changes. This can be achieved using the window.onbeforeunload event.
Legacy Browsers (IE6-8, Firefox 1-3.5)
Set window.onbeforeunload to a function returning a string:
window.onbeforeunload = function() { return "Unsaved changes. Are you sure you want to leave?"; };
Remove the event to disable it:
window.onbeforeunload = null;
Modern Browsers (Chrome, Firefox, etc.)
Enable the prompt:
window.onbeforeunload = function() { return true; };
Disable the prompt:
window.onbeforeunload = null;
To determine if changes have been made, use a validation framework or your own custom event handlers.
jQuery Example:
$('input').change(function() { if ($(this).val() != "") { // Enable the prompt window.onbeforeunload = function() { return true; }; } });
Browser-Specific Considerations
The above is the detailed content of How Can I Prevent Users from Leaving a Web Page with Unsaved Changes?. For more information, please follow other related articles on the PHP Chinese website!