Skip to main content

What does the unload event do?

Definition

unload is 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

javascript
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:

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

3. Important: unload is not beforeunload

Propertybeforeunloadunload
When it firesBefore unloadingDuring unloading
Can stop the departureYes (preventDefault())No
Can show a warningYesNo
Can run codeYes, but with limitsVery limited
Typical tasksWarn about unsaved dataCleanup, 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 localStorage or navigator.sendBeacon()).
  • In some browsers (Safari, iOS) unload is not fired at all - they use pagehide instead.

pagehide

A modern and more reliable event, especially on mobile browsers:

javascript
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

javascript
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 doesThe unload event
When it firesWhen the user leaves the page
Can stop navigationNo
Good forCleanup, logs, saving state
Works asynchronouslyNo (only synchronously or via sendBeacon)
Modern alternativepagehide
Common useAnalytics, saving state

A simple way to remember it: beforeunload - "warn before leaving", unload - "clean up after leaving".

Short Answer

Interview ready
Premium

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