562 字
3 分鐘

HTML dialog 怎麼攔截關閉?requestClose、cancel 與 close 的差別

驗證於

本文目錄

編輯表單放在原生 <dialog> 裡,如果按「關閉」前要檢查草稿,就讓按鈕呼叫 dialog.requestClose(),把攔截條件集中在 cancel 事件。呼叫 dialog.close() 則會直接進入關閉流程。適合在已儲存成功、確定可以離開時使用。 close 事件可用來清理狀態或更新外部畫面。

用同一個 dialog 驗證兩條關閉路徑#

把下列內容存成 HTML 並在支援 requestClose() 的瀏覽器開啟。勾選框用來模擬尚未儲存的狀態。

<!doctype html>
<html lang="zh-Hant">
<meta charset="utf-8">
<title>測試 dialog 關閉</title>
<button id="open">編輯備註</button>
<dialog id="editor" aria-labelledby="heading">
<h1 id="heading">編輯備註</h1>
<label><input id="dirty" type="checkbox" checked> 有未儲存的變更</label>
<button id="request">請求關閉</button>
<button id="finish">模擬已儲存並關閉</button>
<p id="message" role="status"></p>
</dialog>
<pre id="events" aria-live="polite"></pre>
<script>
const editor = document.querySelector('#editor');
const dirty = document.querySelector('#dirty');
const events = document.querySelector('#events');
const message = document.querySelector('#message');
document.querySelector('#open').onclick = () => {
message.textContent = '';
events.textContent = '';
editor.showModal();
};
document.querySelector('#request').onclick = () => editor.requestClose();
document.querySelector('#finish').onclick = () => {
dirty.checked = false;
editor.close('saved');
};
editor.addEventListener('cancel', (event) => {
events.textContent += 'cancel\n';
if (dirty.checked && event.cancelable) {
event.preventDefault();
message.textContent = '請先儲存備註。';
}
});
editor.addEventListener('close', () => {
events.textContent += 'close\n';
});
</script>
</html>

每列以重新開啟視窗開始,事件紀錄會在開啟時清空。

操作預期可觀察結果
勾選狀態按「請求關閉」出現 cancel 與提示,視窗留在畫面上
取消勾選再按「請求關閉」先 cancel 再 close
按「模擬已儲存並關閉」只出現 close

若現有表單用 method="dialog" 結束,額外測試表單提交按鈕。它走表單提交與關閉流程,源頭的驗證應放在 submit,或改成用 type="button" 發出自訂關閉請求。

Esc 和點背景由 closedby 決定入口#

showModal() 開啟的視窗在預設狀態下接受平台的關閉請求,例如桌面 Esc。 closedby="any" 也允許點擊外部來關閉,closedby="none" 則把外部關閉入口關掉,程式仍可以呼叫 requestClose()。鍵盤路徑請用實際按鍵驗收,並觀察 cancel 的 cancelable 值。需要相容舊版瀏覽器時,用功能偵測分支處理,有草稿的按鈕可先走自己的確認介面,確認後再呼叫 close()。關於 cancelable 的除錯方式,可對照滾輪事件與 preventDefault。

參考資料:

WHATWG HTML:dialog 與 requestClose

MDN:HTML dialog

HTML dialog 怎麼攔截關閉?requestClose、cancel 與 close 的差別
https://laplusda.com/posts/html-dialog-requestclose-cancel/
作者
Zero
發佈於
2026-11-16
許可協議
CC BY-NC-SA 4.0