TL;DR: CloseWatcher lets custom web UI respond to the platform's normal “dismiss” action—Escape on a keyboard or Back on an Android device—through one lifecycle. It is a useful progressive enhancement for bespoke drawers, pickers and in-app overlays, but it is not yet Baseline. Prefer native <dialog> and popovers where they fit; use CloseWatcher behind feature detection where custom UI is genuinely necessary.
Modern product interfaces contain plenty of temporary surfaces: navigation drawers, command palettes, filters, account panels and image pickers. Most teams wire a close button, an Escape-key listener and sometimes a history workaround. That produces subtly different behaviour across input methods. The emerging CloseWatcher API gives custom UI a browser-level route for a close request, so the component can behave more like a native dialog.
Table of contents
- What problem does CloseWatcher solve?
- When should a product use it?
- How does its lifecycle work?
- How do you build a robust drawer?
- What are the accessibility and navigation rules?
- What is the browser-support strategy?
What problem does CloseWatcher solve?
CloseWatcher handles a close request: an intent that is native to the user’s device rather than your component. On desktop that is commonly Escape; on Android it may be the system Back action. Built-in UI such as <dialog> and elements using the popover attribute already participate in the browser’s close model. A custom fixed-position <div> does not.
The HTML Standard’s close-request model defines the shared machinery. The CloseWatcher interface exposes it to a component that cannot use native markup. A close request first offers the app a cancellable cancel event, then emits close if it remains valid to dismiss.
That distinction matters. Listening globally for keydown catches only one input path and risks a stale listener closing the wrong surface. Calling history.back() from a drawer changes browser navigation, not just visual state. A watcher makes “there is an open, dismissible surface” an explicit unit of UI state.
A watcher is not a replacement for a visible close control. It adds platform dismissal; it does not make a component discoverable or accessible by itself.
When should a product use it?
Use native primitives first. A confirmation, settings panel or menu is often better implemented with <dialog> or popover; those elements bring established dismissal, focus and top-layer behaviour. For practical patterns, see our guide to CSS anchor positioning and the Popover API and Document Picture-in-Picture.
CloseWatcher earns its keep when the interaction is deliberately custom:
- A full-height mobile navigation drawer with an animated layout shift.
- A multi-step picker whose visual surface does not map to a dialog or popover.
- A canvas or WebGL app overlay that must respect system Back/Escape.
- A legacy design system component you cannot yet replace with a native primitive.
It is particularly attractive when product teams have accumulated separate Escape, close-button and Back handlers. Routing all of them into one closing path creates fewer state combinations to test.
Do not use a watcher simply to block dismissal. If a form has unsaved work, explain the consequence and offer an explicit confirmation. A component that silently refuses Escape or Back is frustrating, especially on touch devices.
How does its lifecycle work?
A CloseWatcher is an EventTarget with three important methods:
requestClose()asks for a normal close. It emitscancel; unless that event is prevented, it then emitsclose.close()emitscloseimmediately, without the cancellable stage.destroy()stops the watcher from receiving future requests.
The MDN API reference is useful here because the names are easy to confuse: use requestClose() when a local button should obey the same “can I close?” rule as the platform; use close() for an unconditional teardown after a confirmed action.
Once close has run, the watcher is deactivated. That makes one watcher per open instance a good model. Create it while opening the surface, retain it with that surface’s state, and clear the reference while closing. Do not allocate watchers at module scope or stack unlimited watchers during repeated renders.
How do you build a robust drawer?
Here is a small, framework-neutral example. It maintains one authoritative finishClose() function and makes the button, Escape and platform Back converge there.
const drawer = document.querySelector('#account-drawer');
const openButton = document.querySelector('#open-account');
const closeButton = drawer.querySelector('[data-close]');
let watcher = null;
function finishClose() {
if (!drawer.open) return;
drawer.open = false;
drawer.setAttribute('aria-hidden', 'true');
watcher?.destroy();
watcher = null;
openButton.focus();
}
function openDrawer() {
if (drawer.open) return;
drawer.open = true;
drawer.setAttribute('aria-hidden', 'false');
watcher = new CloseWatcher();
watcher.addEventListener('cancel', (event) => {
if (drawer.dataset.dirty === 'true') {
event.preventDefault();
showDiscardConfirmation();
}
});
watcher.addEventListener('close', finishClose, { once: true });
drawer.querySelector('a, button, input, select, textarea')?.focus();
}
openButton.addEventListener('click', openDrawer);
closeButton.addEventListener('click', () => watcher?.requestClose());There are two deliberate details here. First, the close button calls requestClose() rather than finishClose() directly, so unsaved-work logic applies consistently. Second, finishClose() is safe to call twice: animations, route changes and an explicit confirmation can otherwise race with the browser’s request.
In React, put the watcher in an effect that runs only while the surface is open, and return cleanup that calls destroy(). Keep the actual close state in React; the watcher should notify it, not become a second source of truth. This is the same principle behind reliable cancellation with AbortSignal.any(): lifecycle ownership must be explicit.
What are the accessibility and navigation rules?
Close handling is only one part of a usable overlay. Before adding a watcher, decide which semantics the surface needs.
Preserve focus deliberately
Move focus into a modal surface when it opens and return focus to the invoking control when it closes. If the drawer is modal, prevent keyboard focus from leaking into obscured page content. Native <dialog> can do much of this work; a custom surface must implement it carefully.
Keep a real close button
An icon button with an accessible name such as aria-label="Close account menu" is still required. Escape and Back are accelerators, not the only exit. Make the button’s event use the same requestClose() route.
Do not confuse Back with page navigation
The platform may use a close request to dismiss the topmost surface before navigating away. That is the expected ordering, but it does not mean every custom UI should rewrite the session history. If your design truly represents a shareable route—say /search?filters=open—model it as routing. Otherwise treat it as transient UI.
Handle nested UI as a stack
Think through a picker inside a drawer: the most recently opened dismissible thing should close first. Avoid a global Escape listener that closes every overlay. The standard explicitly describes interaction with other closeable elements, including dialogs and popovers, so test your real nesting combinations against the specification.
What is the browser-support strategy?
Today this is a progressive enhancement. MDN marks CloseWatcher as not Baseline, so do not make it the only way a user can close UI. Feature-detect it and retain a narrow Escape fallback for browsers without it:
function attachDismissal(onClose) {
if ('CloseWatcher' in window) {
const watcher = new CloseWatcher();
watcher.addEventListener('close', onClose, { once: true });
return () => watcher.destroy();
}
const onKeyDown = (event) => {
if (event.key === 'Escape') onClose();
};
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}The fallback is intentionally modest: it preserves keyboard dismissal but cannot emulate a device Back integration. Keep a visible close control in both paths. Test on the browser/device combinations your analytics say matter, and let support—not novelty—decide when to simplify the fallback.
Also test interactions rather than only individual controls. Open a nested menu, press Escape repeatedly, use the close button midway through an animation, and navigate with a screen reader. Check that focus returns to a useful place and that no invisible surface retains keyboard handlers. These are the failures a single happy-path unit test tends to miss.
What should teams do next?
Audit one custom overlay in your product. If it could be a popover or dialog, modernise it first. If it cannot, identify every close path, funnel them into one state transition, then add CloseWatcher as an enhancement. This produces better behaviour immediately and positions the component for wider platform support later.
The broader lesson is useful beyond this API: the web platform is steadily turning familiar UI behaviours into interoperable primitives. Choosing them intentionally reduces bespoke JavaScript while making products feel more native. That is the same direction behind HTML button commands and the Navigation API.
FAQ
Does CloseWatcher replace the dialog element?
No. Use <dialog> when its semantics and top-layer behaviour fit. CloseWatcher is for custom closable UI that needs to react to platform close requests.
Can CloseWatcher prevent a user from closing an overlay?
It can cancel a particular close request through the cancel event, but use that sparingly. If work would be lost, show an understandable confirmation rather than simply refusing dismissal.
Is CloseWatcher safe to ship now?
Ship it as a feature-detected enhancement, with a visible close control and a keyboard fallback. Do not rely on it as the only dismissal path until support matches your audience.