The HTML onbeforeunload attribute is an event attribute that is fired when the document is about to unload.
Definition and Usage
➔ This allows users to try to leave a page and potentially prevent it or perform cleanup tasks.
➔ When onbeforeunload is triggered, a confirmation dialog box is displayed containing a message such as, "Are you sure you want to leave this page?".
➔ This is typically used in situations where the user may lose unsaved data when they leave the page.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onbeforeunload attribute Example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML onbeforeunload attribute Example</h3>
<h4>Try to navigate away from this page, You will get a confirmation prompt.</h4>
<p><a href="https://w3context.com">w3context.com</a></p>
<script>
window.onbeforeunload = function () {
return "custom mey not support your browser";
};
</script>
</body>
</html>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onbeforeunload | <body> |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onbeforeunload attribute Example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML onbeforeunload attribute Example</h3>
<h4>Try to navigate away from this page, You will get a confirmation prompt if the textfield is non-empty.</h4>
<form>
<input type="text" name="name" id="name" />
</form>
<p><a href="https://w3context.com">w3context.com</a></p>
<script>
const myEventHandler = (event) => {
event.preventDefault();
event.returnValue = true;
};
const nameInput = document.querySelector("#name");
nameInput.addEventListener("input", (event) => {
if (event.target.value !== "") {
window.addEventListener("beforeunload", myEventHandler);
} else {
window.removeEventListener("beforeunload", myEventHandler);
}
});
</script>
</body>
</html>
Click on the "copy" button and try this example in your project.