Next.js Discord

Discord Forum

any way to prevent user leave

Unanswered
Siamese Crocodile posted this in #help-forum
Open in Discord
Siamese CrocodileOP
Is there any way to prevent users leaving the page while editing?

2 Replies

Cape horse mackerel
you can show the warning message before they leave the page
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
window.addEventListener('beforeunload', function (e) {
    // Check if the user has unsaved changes
    if (unsavedChangesExist()) {
        // Display a confirmation message
        var confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
        e.returnValue = confirmationMessage; // Standard for most browsers
        return confirmationMessage; // For some older browsers
    }
});