如何捕获 Windows 资源管理器之类的键盘输入

How to capture keyboard inputs like Windows explorer

我有自定义下拉菜单 select 并捕获 keydown 事件,该事件会在键盘上按下的每个输入触发一个事件。

document.addEventListener('keydown', (event) => {
  const keyName = event.key;
  console.log('keydown event\n\n' + 'key: ' + keyName);
}); 

按"t"和"w"触发事件两个连续的事件。但我需要捕获 "tw" 作为我的搜索词,然后在下拉列表中突出显示它。 (或者) 只是我需要捕获所有连续按下的键。

我正在 Windows 资源管理器中查找内容,快速按 "d" & "e" 突出显示 "Dev Tools".

如何在 JavaScript 中使用适当的超时或其他方式捕获这些?

可能是这样的:

let pressed = [];
let timeoutId;

document.addEventListener('keypress', e => {
  pressed.push(e.key);

  if (timeoutId) {
    clearTimeout(timeoutId);
  }

  timeoutId = setTimeout(() => {
    console.log(pressed.join(''));
    pressed = [];
  }, 400); //300-400ms timeout is optimal
});