Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Close Watcher API: Close Requests, Cancel Events, and User Activation

How the HTML CloseWatcher API handles Escape and close UI, requestClose versus close, cancel events, and history-action activation limits.

The HTML Living Standard defines CloseWatcher so custom overlays (pickers, drawers, inline modals) can participate in the same close request pipeline as built-in UI such as <dialog>, popovers, and similar close watcher stacks. The edition for web developers documents the same surface with examples. This page explains when to use CloseWatcher, how requestClose(), close(), and destroy() differ, and why history-action activation gates cancelable closes.

CloseWatcher: what close requests are for in custom UI

Section titled “CloseWatcher: what close requests are for in custom UI”

A close request is how the platform asks layered UI to dismiss—commonly the Escape key or an equivalent platform signal. Without CloseWatcher, each custom control must duplicate cancel-then-close logic and stay aligned with dialogs and popovers. CloseWatcher centralizes that: you listen for cancel and close, and you route buttons through requestClose() so one code path runs for user-initiated and platform-initiated closes.

Each CloseWatcher instance wraps an internal close watcher that the user agent registers on the relevant global object (typically the Window). That internal watcher is what receives close requests from the platform; your object’s methods and events sit on top of it.

new CloseWatcher(): construction, AbortSignal, and grouping

Section titled “new CloseWatcher(): construction, AbortSignal, and grouping”

How to create a CloseWatcher and tie it to AbortSignal

Section titled “How to create a CloseWatcher and tie it to AbortSignal”

Creates a new CloseWatcher instance.

If the signal option is provided, then watcher can be destroyed (as if by watcher.destroy()) by aborting the given AbortSignal.

— WHATWG HTML (6.10.3 The CloseWatcher interface)

The constructor accepts optional CloseWatcherOptions with an AbortSignal. When the signal aborts, the watcher is destroyed the same way as calling destroy()—useful when the owning component unmounts or a parent operation cancels the overlay.

The normative constructor also requires a fully active document; otherwise it throws InvalidStateError:

If this’s relevant global object’s associated Document is not fully active, then throw an “InvalidStateError” DOMException.

— WHATWG HTML (6.10.3 The CloseWatcher interface)

Why a second CloseWatcher without user activation gets grouped

Section titled “Why a second CloseWatcher without user activation gets grouped”

If any close watcher is already active, and the Window does not have history-action activation, then the resulting CloseWatcher will be closed together with that already-active close watcher in response to any close request. (This already-active close watcher does not necessarily have to be a CloseWatcher object; it could be a modal dialog element, or a popover generated by an element with the popover attribute.)

— WHATWG HTML (The CloseWatcher interface — web developers)

History-action activation is the spec’s name for a stricter flavor of user activation tied to history-consuming gestures. If you spawn another CloseWatcher without it while one is already active, the user agent groups them: one close request closes both. That prevents pages from stacking many independent Escape handlers without user intent.

The developers’ edition illustrates grouping when two instances are created in one click handler without destroying the first:

button2.onclick = () => {
(new CloseWatcher()).onclose = () => { /* ... */ };
(new CloseWatcher()).onclose = () => { /* ... */ };
};

Both close on a single close request. The first watcher created on window.onload without activation is allowed because no other watcher was active yet.

requestClose() versus close() versus destroy()

Section titled “requestClose() versus close() versus destroy()”
Method cancel event close event Stays in close-watcher stack
requestClose() Yes, if not canceled Yes, after successful cancel path Removed after close (as if destroy())
close() Skipped Fired immediately Removed after close
destroy() No No Removed without closing UI logic

requestClose(): platform-like close with optional veto

Section titled “requestClose(): platform-like close with optional veto”

Acts as if a close request was sent targeting watcher, by first firing a cancel event, and if that event is not canceled with preventDefault(), proceeding to fire a close event before deactivating the close watcher as if watcher.destroy() was called.

This is a helper utility that can be used to consolidate cancelation and closing logic into the cancel and close event handlers, by having all non-close request closing affordances call this method.

— WHATWG HTML (The CloseWatcher interface — web developers)

Wire visible “Close” controls to requestClose() so they share the same path as Escape.

close(): force close without running cancel veto logic

Section titled “close(): force close without running cancel veto logic”

Immediately fires the close event, and then deactivates the close watcher as if watcher.destroy() was called.

This is a helper utility that can be used trigger the closing logic into the close event handler, skipping any logic in the cancel event handler.

— WHATWG HTML (The CloseWatcher interface — web developers)

After the user confirms abandonment of unsaved data, call close() from the confirmation flow so you do not recurse through requestClose()’s cancel path.

destroy(): tear down without closing events

Section titled “destroy(): tear down without closing events”

Deactivates watcher, so that it will no longer receive close events and so that new independent CloseWatcher instances can be constructed.

This is intended to be called if the relevant UI element is torn down in some other way than being closed.

— WHATWG HTML (The CloseWatcher interface — web developers)

If you remove the picker from the DOM without a user close gesture, call destroy() so the slot does not leak and later watchers are not grouped incorrectly.

oncancel and onclose: unsaved data and centralized teardown

Section titled “oncancel and onclose: unsaved data and centralized teardown”

Supported event handler IDL attributes:

Event handler Event type
oncancel cancel
onclose close

The web developers’ section shows a picker that keeps teardown in onclose and delegates the close button to requestClose():

const watcher = new CloseWatcher();
const picker = setUpAndShowPickerDOMElement();
watcher.onclose = () => {
chosenValue = picker.querySelector('input').value;
picker.remove();
};
picker.querySelector('.close-button').onclick = () => watcher.requestClose();

That pattern answers a common question: where should cleanup live? In onclose, once any successful close path (button or Escape) has completed.

cancel event: history-action activation and double close requests

Section titled “cancel event: history-action activation and double close requests”

For abuse prevention purposes, this event is only cancelable if the page has history-action activation, which will be lost after any given close request. This ensures that if the user sends a close request twice in a row without any intervening user activation, the request definitely succeeds; the second request ignores any cancel event handler’s attempt to call preventDefault() and proceeds to close the CloseWatcher.

— WHATWG HTML (The CloseWatcher interface — web developers)

Implications for authors:

  • Unsaved-data prompts via preventDefault() on cancel only work when e.cancelable is true—check before vetoing.
  • A second Escape (or second close request) without a new gesture cannot be blocked indefinitely; design UX so confirmation does not rely on trapping the user.

Typical async confirmation pattern from the spec narrative: veto on cancel, ask the user, then call watcher.close() if they confirm—close() bypasses cancel on that second step.

  • Using close() on a user-facing X button when you still want unsaved-data checks—prefer requestClose() for affordances that should mirror Escape.
  • Creating nested watchers without activation and expecting independent Escape behavior—grouping closes them together.
  • Forgetting destroy() after removing UI by other means—leaves a phantom watcher and causes surprising grouping later.
  • Assuming cancel is always cancelable—without history-action activation, preventDefault() cannot hold off platform close requests.
  • Constructing on a non–fully-active document (e.g. detached or BFCache edge cases)—constructor throws InvalidStateError.

How close watchers relate to dialog and popover

Section titled “How close watchers relate to dialog and popover”

The same grouping rule names modal dialog and popover close watchers explicitly. Custom CloseWatcher code should assume it shares the global close stack with those elements, not a private Escape channel. If a dialog is open, your watcher may be grouped or ordered according to user agent close-watcher rules; test combined UI rather than only isolated pickers.

  1. Open a page that uses CloseWatcher in a current Chromium-based browser or other engine that implements the HTML close watcher stack (see Capabilities for how Chrome documents web platform API status).

  2. Open the overlay, press Escape once, and confirm whether cancel runs and whether close follows when you do not call preventDefault()—compare with The CloseWatcher interface — web developers.

  3. Repeat with unsaved-state logic: verify the first close request can show a prompt only when event.cancelable is true, then verify a second close request without intervening activation still dismisses, per the abuse-prevention rules in 6.10.3 The CloseWatcher interface.

  4. Create two CloseWatcher instances in one handler without calling destroy() on the first; send one close request and confirm both onclose handlers run (grouping behavior).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match the HTML specification or behaves differently in your browser, email yimasynthetic@gmail.com with the page URL and the exact statement you are questioning so it can be corrected or clarified.