We have often wondered if it is possible to display a confirmation dialog when a user is about to leave our page. This is especially useful in situations where the user is uploading or downloading a file, filling out a long form, or waiting for a critical process to finish. In these cases, we need the user to stay—or at least to make a conscious decision before leaving. For this purpose, JavaScript's beforeunload event exists, triggering right at the moment the user attempts to close the window or browser tab.
The beforeunload event fires precisely when the user tries to leave the page, whether by closing the browser, the tab, or navigating to another URL. At that exact instant, we can display a confirmation dialog to ask if they are sure they want to exit. That being said, it is a tool that must be used carefully: overusing it or taking it out of context can be annoying and harm the user experience.
The confirmation before closing a tab—also known as a beforeunload dialog—is a small alert that appears when the user attempts to close the browser, the tab, or refresh the page while something important is happening. It is a simple yet effective tool: used well, it can prevent accidental drop-offs and interrupted processes that are lost beyond recovery.
Golden rule: if the user can lose information upon closing, show them a confirmation dialog.
When to use it and when to avoid it
You should use beforeunload when:
- The user is uploading a file.
- There is a critical process running (downloads, conversions, report generation).
- There is a long or time-consuming form to fill out that has not yet been saved.
- It involves content or progress that the user could accidentally lose.
You should avoid using it when:
- You want to retain the user in an aggressive or manipulative manner.
- Your sole objective is to prevent them from leaving your website for marketing reasons (terrible idea: it damages trust and long-term SEO).
- The user's action does not involve data loss or real consequences.
Restrictions and recent changes in modern browsers
This is probably the most important point you should know before implementing it: modern browsers no longer allow custom messages in the beforeunload dialog.
That is, even if you write a perfectly crafted text inside event.returnValue, Chrome, Firefox, or Safari will simply ignore it and display a generic message controlled by the browser itself. This was a deliberate decision to prevent sites from using misleading or high-pressure messages to manipulate the user. So do not waste time writing the perfect text: it will not be displayed.
How the beforeunload event works in JavaScript
Its usage is very simple. It is enough to register the event on window and assign a value to the event.returnValue property inside the handler. That value is what, in theory, would appear in the dialog—although, as we have seen, modern browsers ignore it and show their own generic text. If you do not assign a value, the event still occurs, but the browser will not interrupt the user with an alert.
The modern, recommended way is to use addEventListener:
window.addEventListener("beforeunload", function (event) {
event.returnValue = "Are you sure you want to go out?";
});And the classic version with onbeforeunload, useful if you need compatibility with older browsers or environments:
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = "Are you sure you want to go out?";
}
// For Safari
return "Are you sure you want to go out?";
};A good practice is to enable the event only when necessary and remove it once the critical process has finished, using removeEventListener. This prevents the dialog from appearing when it no longer makes sense.
Behavior by browser
- Chrome: completely ignores custom text in
event.returnValueand displays only its generic message. - Firefox: practically identical behavior to Chrome since version 44+.
- Safari: allows the
returnin some specific scenarios, although its behavior may vary between versions. - Mobile (Android/iOS): support is very limited or practically non-existent; in most cases, the event is completely ignored.
The key is not to activate it permanently. It should only be active when the user is engaged in an important process whose interruption implies losing what they were doing. Dynamically activating and deactivating it is the proper way to handle it.
More respectful alternatives to protect user progress
If the context does not justify a beforeunload or if you want to complement it, these alternatives are usually less intrusive and more pleasant for the user:
- Visible progress bars that communicate the status of the ongoing process.
- Informational messages within the page itself warning about unsaved changes.
- Auto-saving forms so that the user never loses what they have typed.
- Internal confirmations (custom modals or dialogs) before the user navigates to another section within the same application.
On more than one occasion I have opted for these alternatives instead of
beforeunload, especially when the goal was not critical or when I wanted the experience to feel fluid rather than interrupted.
Frequently Asked Questions
- Does Chrome allow custom messages in the dialog?
- No. For several years now, Chrome ignores the content of
event.returnValueand displays only its own generic message.
- No. For several years now, Chrome ignores the content of
- Does it work on mobile devices?
- In most mobile browsers (Android and iOS), support is virtually non-existent. It is not something you should rely on to protect data in mobile environments.
- Is it legal to use it?
- Yes, as long as you do not use it to manipulate or deceive the user. Using it to protect real user data is completely justified.
- How can I avoid abusing it?
- Activate it only during interactions that truly justify it—such as an ongoing file upload or a form with unsaved changes—and remove it using
removeEventListeneras soon as the process completes.
- Activate it only during interactions that truly justify it—such as an ongoing file upload or a form with unsaved changes—and remove it using
Conclusion
The beforeunload event is a small but powerful tool. Well-implemented, it prevents loss of progress, unexpected errors, and accidental drop-offs that users later regret. In my case, it has been particularly useful on my blog and my course and book pages, where I need the user to remain until everything is properly loaded or saved.
The secret is moderation: activate it only when it genuinely adds value, understand its limitations in modern browsers—which ignore any custom messages—and combine it with other UX techniques like auto-saving or progress bars whenever the context allows.