onbeforeunload 事件在用戶離開頁面(關閉標籤、刷新、跳轉、提交表單等)前觸發,返回字串可彈出確認對話框,讓用戶選擇留下或離開。
<script>
var g_blnCheckUnload = true;
function RunOnBeforeUnload() {
if (g_blnCheckUnload) {
window.event.returnValue = '您有未保存的內容,確定要離開嗎?';
}
}
</script>
<body onbeforeunload="RunOnBeforeUnload()"></body>
window.addEventListener('beforeunload', function(e) {
if (g_blnCheckUnload) {
e.preventDefault(); // 標準要求
e.returnValue = ''; // Chrome/Firefox 顯示通用提示,自定義文本已被大多數瀏覽器忽略
}
});
window.close()、location.href=...、location.reload()、form.submit() 等true,避免打擾正常導航。beforeunload 發送 navigator.sendBeacon 保存草稿。正確使用 beforeunload 能有效防止用戶誤操作丟失數據。