window.onbeforeunload當用戶嘗試關閉標籤、刷新、跳轉鏈接時觸發。返回字符串(舊版)或設置 event.returnValue(現代標準)可彈出確認對話框。
window.addEventListener('beforeunload', function(e) {
// 1. 只有頁面有未保存變更時才提示
if (hasUnsavedChanges()) {
// 2. 現代瀏覽器忽略返回字符串,自動顯示通用提示
// 3. 必須設置 returnValue (Chrome/Firefox/Edge/Safari 統一行為)
e.returnValue = '您有未保存的內容,確定要離開嗎?';
// 4. 兼容舊版 IE/FF
return e.returnValue;
}
});
// 示例:表單修改檢測
var formOriginal = $("form").serialize();
function hasUnsavedChanges() {
return $("form").serialize() !== formOriginal;
}
// 保存後重置
$("form").on("submit", function() {
formOriginal = $(this).serialize();
});
// 正確移除:同時清除事件監聽器與 onbeforeunload 屬性
function disableUnloadPrompt() {
window.removeEventListener('beforeunload', beforeUnloadHandler);
window.onbeforeunload = null;
}
// 若用 jQuery 綁定
$(window).off('beforeunload', beforeUnloadHandler);
e.returnValue = '' 即可觸發,內容不再顯示。| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
window.onbeforeunload = null; 後直接關閉 | 若之前用 addEventListener 綁定,onbeforeunload 清空不生效 | 必須 removeEventListener 對應的處理函數 |
在 alert()/confirm() 中阻塞 | 瀏覽器禁止在 beforeunload 中彈窗,會被忽略 | 只能返回字符串/設置 returnValue |
綁定在 <body onbeforeunload> | 不推薦,內容安全策略 (CSP) 可能阻止內聯腳本 | JS 中統一綁定 |
beforeunload 不會在客戶端路由跳轉 (hashchange/pushState) 時觸發。需在路由守衛中手動攔截:
// Vue Router 示例
router.beforeEach((to, from, next) => {
if (hasUnsavedChanges()) {
if (confirm('有未保存更改,確定離開?')) next();
else next(false);
} else next();
});