Home >Web Front-end >JS Tutorial >How to Prevent Accidental Navigation Away from a Page with Unsaved Changes?

How to Prevent Accidental Navigation Away from a Page with Unsaved Changes?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 14:20:10913browse

How to Prevent Accidental Navigation Away from a Page with Unsaved Changes?

How to Display "Are you sure you want to navigate away from this page?" When Changes Are Committed

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;

Legacy Browser Support (Deprecated)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn