Browser Exit Confirmation
Prevent accidental data loss. This script triggers the native browser confirmation dialog ("Are you sure you want to leave?") when a user attempts to close the window.
Step 1: Click anywhere on this page (interaction is required).
Step 2: Try to close this tab or refresh the page.
A browser dialog should appear asking you to confirm.
Copy the Script
<script>
window.onbeforeunload = function() {
// The text string is ignored by most modern browsers
// but returning a string triggers the generic dialog.
return "Are you sure you want to leave?";
};
</script>
Frequently Asked Questions
No. Modern browsers (Chrome, Firefox, Edge) now ignore custom text strings in this dialog to prevent scams. They only show a generic 'Changes you made may not be saved' message.
Sometimes, but mobile browser behavior varies. It is generally less reliable on mobile Safari compared to desktop.
The user must have interacted with the page (clicked or typed) at least once for the browser to allow this event to fire.