Home >Web Front-end >JS Tutorial >How to Prevent Accidental Navigation Away from a Page with Unsaved Changes?
In a modern web environment, displaying custom navigation prompts is considered a security concern, and browsers no longer support this functionality. Instead, browsers will only display generic messages. To enable or disable the navigation prompt, simply use the following code:
// Enable navigation prompt window.onbeforeunload = function() { return true; }; // Remove navigation prompt window.onbeforeunload = null;
For compatibility with older browsers such as IE6-8 and Firefox 1-3.5, you can use the following code to display a custom navigation prompt:
var confirmOnPageExit = function (e) { // Define the message to be displayed var message = 'Confirm your navigation away from the page'; // Handle compatibility with older browsers if (e) { e.returnValue = message; } // Return the message return message; }; // Enable the navigation prompt window.onbeforeunload = confirmOnPageExit; // Disable the navigation prompt window.onbeforeunload = null;
To check for changed values when using a validation framework like jQuery, you can use code similar to the following:
$('input').change(function() { // Check if the input value is not empty if( $(this).val() != "" ) { // Enable the navigation prompt window.onbeforeunload = confirmOnPageExit; } });
The above is the detailed content of How to Prevent Accidental Navigation Away from a Page with Unsaved Changes?. For more information, please follow other related articles on the PHP Chinese website!