The function of the front end to record the keys being pressed by the user

I have a need to detect the keystroke the user is pressing, and if it is a combination of keys (such as command + shift + p),), I will perform a certain operation.

but encountered a problem, that is, the keyup event of the composite key did not trigger, but only triggered the keydown.

Code:

const pressingKeyCode = {};

const COMMAND = 91;

const SHIFT = 16;

const P = 80;

window.addEventListener("keydown", e => {
  console.log("keydown", e.keyCode);
  pressingKeyCode[e.keyCode] = true;
  if (
    pressingKeyCode[COMMAND] &&
    pressingKeyCode[SHIFT] &&
    pressingKeyCode[P]
  ) {
    console.log("");
  }
});

function handleKeyUp(e) {
  console.log("keyup", e.keyCode);
  pressingKeyCode[e.keyCode] = false;
}

window.addEventListener("keyup", handleKeyUp);
there is no problem with a single keystroke

reproducible demo address: https://codepen.io/zhipenglu/.

Apr.22,2021

since my side is Windows, I use CTRL's Keycode (17)

.

did not understand the meaning of the title, the keyup event of the compound key did not trigger
I tried to replace it here, there is no problem. https://codepen.io/mscststs/p.

Mac exclusive?

clipboard.png


window.addEventListener('keydown',e => {
    const keyCode_S = 83;
    console.log('keydown', e.keyCode);
    if(e.ctrlKey && e.keyCode == keyCode_S){
        e.preventDefault();
        alert('');
    }
});

has cooled the problem?


I opened your reproducible link and added a few lines of code to test it and found that the keyup of the compound button could be detected.

const pressingKeyCode = {};

const COMMAND = 91;

const SHIFT = 16;

const P = 80;

window.addEventListener('keydown', e => {
  console.log('keydown', e.keyCode);
  pressingKeyCode[e.keyCode] = true;
  if (
    pressingKeyCode[COMMAND] &&
    pressingKeyCode[SHIFT] &&
    pressingKeyCode[P]
  ) {
    console.log('');
  }
});

function handleKeyUp(e) {
  console.log('keyup', e.keyCode);
  pressingKeyCode[e.keyCode] = false;
  if (
    !pressingKeyCode[COMMAND] &&
    !pressingKeyCode[SHIFT] &&
    !pressingKeyCode[P]
  ) {
    console.log('');
  }
}

window.addEventListener('keyup', handleKeyUp);

when I lift three fingers at the same time, I can print ha

.
Menu