How to detect Escape
document.addEventListener('keydown', (event) => {
if (event.key === "Escape") {
// Escape was pressed
}
});
Use event.key to react to what the key means (it follows the keyboard layout) and event.code for its physical position, for example WASD in games. keyCode and which are deprecated: they still work, but their values differ between browsers and layouts.
How browsers treat Escape
Escape is the standard way to close dialogs, menus and popovers. A native <dialog> closes on Escape by itself and fires a cancel event. Browsers also use Escape to leave full screen, and that press usually isn’t delivered to the page.
In React
<input onKeyDown={(e) => { if (e.key === "Escape") { /* … */ } }} />