Sự kiện beforeunload cho phép hiển thị hộp thoại xác nhận khi người dùng rời trang (reload, close tab, navigate). Trình duyệt hiện thông báo mặc định, nội dung tùy chỉnh bị hạn chế.
Ví dụ
Form đăng nhập, cảnh báo khi reload:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Unsaved changes alert</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
input { margin: 10px; }
</style>
</head>
<body onbeforeunload="return pageUnload()">
<h1>Cảnh báo thay đổi chưa lưu trong Form</h1>
<form>
Username <input type="text" /><br />
Password <input type="password" /><br />
<button type="submit">GỬI</button>
</form>
<br />
<script>
function pageUnload() {
return 'Dữ liệu trên trang sẽ mất nếu bạn rời đi';
}
</script>
</body>
</html>
Kết quả
Khi nhấn F5 hoặc đóng tab, trình duyệt hiển thị hộp thoại: "Dữ liệu trên trang sẽ mất nếu bạn rời đi" (wording tùy browser).
Best practice: Chỉ gán beforeunload khi form thực sự dirty (đã thay đổi). Dùng addEventListener('beforeunload', e => { e.preventDefault(); e.returnValue = ''; }) chuẩn hiện đại.