What does the unload event do?
Definition
unloadis an event that occurs when the document is unloaded from the browser's memory. That means the user:
- closes the tab,
- reloads the page (
F5),- follows another link,
- or navigates to another page in an SPA during a full reload.
1. Usage example
window.addEventListener('unload', () => {
console.log('The page is unloading...');
});This fires at the very last moment, when the page is already leaving memory.
2. Typical use cases
- sending statistics or logs "before the user leaves";
- saving data to
localStorage/sessionStorage; - closing connections, WebSockets, freeing resources.
For example:
window.addEventListener('unload', () => {
localStorage.setItem('lastVisited', new Date().toISOString());
});3. Important: unload is not beforeunload
| Property | beforeunload | unload |
|---|---|---|
| When it fires | Before unloading | During unloading |
| Can stop the departure | Yes (preventDefault()) | No |
| Can show a warning | Yes | No |
| Can run code | Yes, but with limits | Very limited |
| Typical tasks | Warn about unsaved data | Cleanup, logging |
4. Limitations and nuances
Modern browsers strongly restrict unload so it doesn't slow down page closing:
- Asynchronous actions (
fetch,setTimeout) do not work - the browser does not wait for them to finish. - You cannot show a dialog or a modal window.
- Only synchronous operations work (for example, writing to
localStorageornavigator.sendBeacon()). - In some browsers (Safari, iOS)
unloadis not fired at all - they usepagehideinstead.
5. Recommended alternative
pagehide
A modern and more reliable event, especially on mobile browsers:
window.addEventListener('pagehide', (event) => {
console.log('The page is hidden or unloaded');
});It works even when switching to another tab, and is more reliable than unload.
6. Example: sending analytics when the page closes
window.addEventListener('unload', () => {
navigator.sendBeacon('/analytics', JSON.stringify({ event: 'exit' }));
});navigator.sendBeacon() is the only safe way to send data to the server when the page closes,
because it works asynchronously, but the browser still guarantees delivery.
Summary
| What it does | The unload event |
|---|---|
| When it fires | When the user leaves the page |
| Can stop navigation | No |
| Good for | Cleanup, logs, saving state |
| Works asynchronously | No (only synchronously or via sendBeacon) |
| Modern alternative | pagehide |
| Common use | Analytics, saving state |
A simple way to remember it:
beforeunload- "warn before leaving",unload- "clean up after leaving".
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.