onunload 與 onbeforeunload 都在頁面刷新或關閉時觸發,可以在 script 中通過 window.onunload 指定,也可以直接寫在 <body> 標籤上。關鍵差別在於執行順序與能否「攔住」用戶。
onload。onbeforeunload,最後 onunload。onbeforeunload,然後 onunload,最後 onload。onbeforeunload 是在「正要去伺服器讀取新頁面」時觸發,此時還沒開始讀取;onunload 則是新頁面已經讀到、即將替換當前頁面時觸發。因此 onunload 無法阻止頁面更新或關閉,而 onbeforeunload 可以。
瀏覽器支援:Firefox 與 IE 都支援,Opera 早期版本尚未支援。
用法:
object.onbeforeunload = handler;
<element onbeforeunload="handler"></element>
行為:觸發時彈出一個帶有「確定」與「取消」的對話框,確定則離開,取消則留在本頁。handler 的返回值會作為對話框的提示文字。
常見觸發時機:
window.close、location.replace、location.reload、form.submit 等方法window.open 打開新頁面並傳入本視窗名稱時location.href 賦值時可用於:BODY、FRAMESET、window
平台支援:IE4+/Win、Mozilla 1.7a+、Netscape 7.2+、Firefox 0.9+
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onbeforeunload 測試</title>
<script>
function checkLeave() {
event.returnValue = "確定離開當前頁面嗎?";
}
</script>
</head>
<body onbeforeunload="checkLeave()">
</body>
</html>
用戶關閉頁面時觸發,觸發時機與 onbeforeunload 幾乎相同(見上面的清單)。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onunload 測試</title>
<script>
function checkLeave() {
alert("歡迎下次再來!");
}
</script>
</head>
<body onunload="checkLeave()">
</body>
</html>
window.onbeforeunload = function() {
alert("===onbeforeunload===");
if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
alert("你關閉了瀏覽器");
} else {
alert("你正在刷新頁面");
}
};
思路是:判斷觸發 onbeforeunload 時滑鼠是否落在關閉按鈕的位置上,或者用戶是否按了 ALT+F4。符合則認為是關閉網頁,否則認為是刷新。
幾點實務提醒:這種基於座標的判斷非常依賴瀏覽器與作業系統版本,穩定性有限。另外,現代瀏覽器出於安全與體驗考慮,已經大幅限制 onbeforeunload:只有在頁面產生過用戶交互(表單輸入、點擊等)之後,瀏覽器才會顯示確認框,而且提示文字統一由瀏覽器控制,自訂文案會被忽略。移動端 Safari 更是完全不觸發。因此它適合做「未保存內容提醒」,不適合承載關鍵業務邏輯。