This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.
The above implies that the event is cancelable, but...
According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.
And even then, if you are indeed doing that...
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
However, unlike the unload event, there is a legitimate use case for the beforeunload event: the scenario where the user has entered unsaved data that will be lost if the page is unloaded.
It is recommended that developers listen for beforeunload only in this scenario, and only when they actually have unsaved changes, so as to minimize the effect on performance. See the Examples section below for an example of this.
See the Page Lifecycle API guide for more information about the problems associated with the beforeunload event.
Example
In this example a page listens for changes to a text input. If the element contains a value, it adds a listener for beforeunload. If the element is empty, it removes the listener:
const beforeUnloadListener = (event) => {
event.preventDefault();
return event.returnValue = "Are you sure you want to exit?";
};
const nameInput = document.querySelector("#name");
nameInput.addEventListener("input", (event) => {
if (event.target.value !== "") {
addEventListener("beforeunload", beforeUnloadListener, {capture: true});
} else {
removeEventListener("beforeunload", beforeUnloadListener, {capture: true});
}
});