You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模拟Escape键无法关闭HTML <dialog>模态框:原因与解决办法

模拟Escape键关闭<dialog>元素的问题

我尝试通过模拟按下escape键来关闭模态<dialog>元素,以下是示例代码:

JavaScript 代码

document.addEventListener("keydown", (e) => {
  console.log(e)
});
document.addEventListener("keyup", (e) => {
  console.log(e)
});
document.addEventListener("keypress", (e) => {
  console.log(e)
});

const dialog = document.querySelector(`dialog`);

const openDialogButton = document.querySelector(`#open-dialog-button`);
openDialogButton.addEventListener("click", () => {
  dialog.showModal();
});

const syntheticEscapeButton = document.querySelector(`#synthetic-escape-button`);
syntheticEscapeButton.addEventListener("click", () => {
  document.dispatchEvent(
    new KeyboardEvent("keydown", {
      altKey: false,
      code: "Escape",
      ctrlKey: false,
      isComposing: false,
      key: "Escape",
      location: 0,
      metaKey: false,
      repeat: false,
      shiftKey: false,
      which: 27,
      charCode: 0,
      keyCode: 27,
    }));
  document.dispatchEvent(
    new KeyboardEvent("keyup", {
      altKey: false,
      code: "Escape",
      ctrlKey: false,
      isComposing: false,
      key: "Escape",
      location: 0,
      metaKey: false,
      repeat: false,
      shiftKey: false,
      which: 27,
      charCode: 0,
      keyCode: 27,
    }));
});

const closeDialogButton = document.querySelector(`#close-dialog-button`);
closeDialogButton.addEventListener("click", () => {
  dialog.close();
});

HTML 代码

<input id="input-1" type="text">

<button id="open-dialog-button">Open Dialog</button>

<dialog>
  <div id="dialog-body">
    <p>Press the escape key to close the dialog box.</p>
    <input id="input-2" type="text">
    <button id="synthetic-escape-button">Press Synthetic Escape</button>
    <button id="close-dialog-button">Close Dialog</button>
  </div>
</dialog>

现象

  • 点击“Open Dialog”按钮后按escape键,对话框会关闭。
  • 点击“Open Dialog”按钮后点击“Press Synthetic Escape”按钮,对话框不会关闭。

两种操作下键盘事件监听器都会触发。为何<dialog>在第一种情况关闭但第二种不行?如何让合成escape键像手动操作一样关闭<dialog>?

背景

这用于我编写的自动化测试,需原生JavaScript解决方案,使用Windows 10系统下的Firefox。

更新

TestCafe最新版本(v3)默认使用原生事件,但仅支持部分浏览器,Firefox不在其中。切换到Chrome后可实现模拟用户按键效果,此信息仅供参考,仍需原问题的解决方案。


内容的提问来源于stack exchange,提问作者Daniel Kaplan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:55:36