【问题标题】:Escape key fired when clicked on a link in non-focused window在非焦点窗口中单击链接时触发退出键
【发布时间】:2022-12-18 14:48:25
【问题描述】:

我不知道这是错误还是功能,但似乎 Chrome 108.0.5359.95 以及 MS Edge 107.0.1418.56 在窗口未处于焦点并单击该窗口中的链接时触发 Escape keydown/up 事件.下面是一个简单的演示:

onkeydown = onEvent;
onkeyup = onEvent;
onkeypress = onEvent;

function onEvent(e)
{
  const obj = {};
  for(let i in e)
    if (e[i] === null || typeof e[i] != "object")
      obj[i] = e[i];

  document.getElementById("" + e.type).value = JSON.stringify(obj, true, 2);
  console.log(e);
}

onblur = e => document.querySelectorAll("textarea").forEach(el => el.value = "");
textarea
{
  width: 100%;
  height: 30vh;
}
Make sure this window is not focused (click on taskbar) then <a id="link" href="#">click and hold this</a>
<textarea id="keydown" placeholder="onkeydown"></textarea>
<textarea id="keyup" placeholder="onkeyup"></textarea>
<textarea id="keypress" placeholder="onkeypress"></textarea>

有没有办法防止这些事件发生或至少检测实际用户是否按下了escape键?

【问题讨论】:

    标签: javascript google-chrome microsoft-edge


    【解决方案1】:

    Event 接口的 isTrusted 只读属性是一个布尔值 当事件由用户操作生成时为 true 的值,以及 当事件由脚本创建或修改或分派时为 false 通过 EventTarget.dispatchEvent()。

    Event.isTrusted MDN Docs

    window.addEventListener('keydown', function(event) {
      if (event.key === 'Escape' && event.isTrusted) {
        console.log('Escape Key is pressed by user')
      }
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2013-09-09
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多