demo · v139
Form Guard
A dialog containing a half-filled form should warn before closing. The declarative command="request-close" fires the dialog's cancel event before closure — your listener can preventDefault() to keep the dialog open. No JS to wire the button itself.
click "Open form" to start, then type something and try to close.
the markup
<dialog id="dlg">
<form>
<input name="msg">
<!-- v139: command="request-close" fires cancel event, doesn't bypass it -->
<button commandfor="dlg" command="request-close">Close</button>
</form>
</dialog>
<script>
dlg.addEventListener("cancel", e => {
if (msg.value && !confirm("Discard your message?")) {
e.preventDefault(); // dialog stays open
}
});
</script>
why this beats the old way
Before: a "Close" button called dlg.close(), which skipped the cancel event entirely. Authors had to call dlg.requestClose() in JS — meaning every button needed a JS handler. v139 adds command="request-close" so the same intent is expressed declaratively. The cancel event fires, your listener decides, and only then does the dialog close.