When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The beforeunload event happens when the document is about to be unloaded.
When beforeunload happens
The document is about to be unloaded.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<p>Try the relevant browser action described below.</p>
<p id="event-status" role="status">Waiting for beforeunload...</p>
<script>
const eventTarget = window;
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("beforeunload", (eventDetails) => {
eventStatus.textContent = "beforeunload event received";
console.log(eventDetails.type, eventDetails.target);
});
}
</script>
Reading the code
The browser listens for beforeunload on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Navigation away can trigger it; modern browsers restrict confirmation prompts and may not fire it reliably.
Calling preventDefault and setting returnValue can request a browser-owned prompt, but browsers restrict it and may omit the event.
Some events need a specific browser condition, another tab or window, or a Web Component to reproduce. Read the trigger steps carefully before deciding that an event handler is not working.
Try it in your browser
Open the page, show the Console panel, and follow this test: Navigation away can trigger it; modern browsers restrict confirmation prompts and may not fire it reliably. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
beforeunloadto fire without its required user action or browser condition. - Navigation away can trigger it; modern browsers restrict confirmation prompts and may not fire it reliably.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
beforeunloadreports the document is about to be unloaded.addEventListener("beforeunload", ...)listens for the event on the appropriate target.- Navigation away can trigger it; modern browsers restrict confirmation prompts and may not fire it reliably.