Skip to main content

What does the beforeunload event do?

Definition

beforeunload is an event that fires right before the current page is unloaded from the browser's memory. It happens when the user:

  • closes the tab or window,
  • reloads the page,
  • follows a link or enters a new URL.

1. A simple example

javascript
window.addEventListener('beforeunload', (event) => { event.preventDefault(); event.returnValue = ''; // required! });

After this, the browser shows a leave-confirmation dialog:

Are you sure you want to leave this page? Changes you made may not be saved.

Important:

  • Modern browsers do not let you set your own text in this dialog. (you used to be able to set event.returnValue = 'Are you sure?', but that is now ignored).
  • This is done for security and UX reasons - so sites cannot "blackmail" the user ("stay with us!").

2. When to use it

Used when the user might lose unsaved changes, for example:

  • editing text but hasn't clicked "Save";
  • filling out a form;
  • writing a comment;
  • doing something in an app with unsaved state.
javascript
let formChanged = false; document.querySelector('form').addEventListener('input', () => { formChanged = true; }); window.addEventListener('beforeunload', (e) => { if (formChanged) { e.preventDefault(); e.returnValue = ''; } });

Now, if the user has changed the form and tries to leave, a warning appears.

3. An example without a warning (just a "hook" before leaving)

If you just need to run cleanup or logic before unloading (without a dialog):

javascript
window.addEventListener('beforeunload', () => { localStorage.setItem('lastVisited', new Date().toISOString()); });

This event is the last point where you can save data to localStorage or sessionStorage.

4. The difference between beforeunload and unload

EventWhen it firesCan it stop the navigation?When to use it
beforeunloadBefore unloadingYes (via preventDefault())Warning about unsaved data
unloadAfter unloading has startedNoCleanup, analytics, logging

Limitations

  • You cannot use alert() or confirm() inside beforeunload - browsers block them.
  • You should not run asynchronous operations (requests, fetch) - they won't have time to finish.
  • It works only in the browser window/tab, not in frames.
  • Better not to use it unless necessary - it is UX spam.

Summary

What it doesThe beforeunload event
When it firesRight before the user leaves the page
What it's forWarning about the loss of unsaved data
How to stop itevent.preventDefault() + event.returnValue = ''
Custom textNot allowed (the browser shows a standard one)
When it doesn't fitFor asynchronous actions - they won't have time to run

Remember it simply: beforeunload is a "last chance" to tell the browser: "Wait! The user has unsaved data."

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.