Custom Confirmation Dialog for Navigation Blocking
Illustrate the creation and use of a custom confirmation dialog that is triggered by navigation blocking, enhancing the user experience compared to default browser alerts.
window.addEventListener('beforeunload', function(e) {
// Check for unsaved changes or conditions to trigger the custom dialog
if (hasUnsavedChanges()) {
e.preventDefault();
e.returnValue = '';
}
});
This piece of code listens for the 'beforeunload' event, which is fired when the user attempts to leave the page. If there are unsaved changes detected by the function hasUnsavedChanges(), it triggers the browser's default confirmation dialog by setting e.returnValue to an empty string. This is where you would integrate your custom dialog logic in a real application.
function hasUnsavedChanges() {
return document.querySelector('input').value !== '';
}
A simple helper function to check if there are unsaved changes. In this case, it simply checks if any input field is not empty. This is for illustration; in a real application, you might check more conditions or integrate with a state management library.
window.addEventListener('beforeunload', function(e) {
if (!hasUnsavedChanges()) return;
const confirmationMessage = 'You have unsaved changes! Are you sure you want to leave?';
e.preventDefault();
if (confirm(confirmationMessage)) return;
e.returnValue = '';
});
This modified listener introduces a custom confirmation using the window.confirm() function for simplicity. If there are unsaved changes, it asks the user if they are sure they want to leave. This example utilizes the browser's built-in confirm dialogue for simplicity, but the same logic can be applied to trigger a more complex, custom-designed confirmation dialogue.