CloseWatcher
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The CloseWatcher interface listens and responds to close requests.
Some UI components have "close behavior", meaning that the component appears, and the user can close it when they are finished with it. For example: sidebars, popups, dialogs, or notifications.
Users generally expect to be able to use a particular mechanism to close these elements, and the mechanism tends to be device-specific. For example, on a device with a keyboard it might be the Esc key, but Android might use the back button. For built-in components, such as popover or <dialog> elements, the browser takes care of these differences, closing the element when the user performs the close action appropriate for the device. However, when a web developer implements their own closable UI component (for example, a sidebar), it is hard to implement this kind of device-specific close behavior. The CloseWatcher interface solves this problem by delivering a close event to the when the user executes the close action for the device.
The CloseWatcher interface inherits from EventTarget.
Constructor
CloseWatcher()Experimental-
Creates a new
CloseWatcherinstance.
Instance methods
This interface also inherits methods from its parent, EventTarget.
CloseWatcher.requestClose()Experimental-
Fires a
cancelevent and if that event is not canceled withEvent.preventDefault(), proceeds to fire acloseevent, and then finally deactivates the close watcher as ifdestroy()was called. CloseWatcher.close()Experimental-
Immediately fires the
closeevent, without firingcancelfirst, and deactivates the close watcher as ifdestroy()was called. CloseWatcher.destroy()Experimental-
Deactivates the close watcher so that it will no longer receive
closeevents.
Events
Examples
Processing close requests
In this example, you have your own UI component (a picker) and you want to support both, the platform's default close method (e.g. the Esc key) and your custom close method (a close button).
You create a CloseWatcher to handle all close events.
The onclick handler of your UI component can call requestClose to request a close and to route your close request through the same onclose handler the platform close method uses.
const watcher = new CloseWatcher();
const picker = setUpAndShowPickerDOMElement();
let chosenValue = null;
watcher.onclose = () => {
chosenValue = picker.querySelector("input").value;
picker.remove();
};
picker.querySelector(".close-button").onclick = () => watcher.requestClose();
Specifications
| Specification |
|---|
| HTML Standard # closewatcher |
Browser compatibility
BCD tables only load in the browser
See also
closeevent onHTMLDialogElement