1

I'm trying to simulate user keyboard input and have read through the answers for this post, but the answer(s) don't work for special keys such as $. For example, when I try to simulate pressing $ with

let data = {
    code: "Digit4",
    key: "$",
    keyCode: 52,
    shiftKey: true
};
let key_event = new KeyboardEvent("keypress", data);
myElement.dispatchEvent(key_event);

4 gets pressed/printed, not $.

If I change keypress to keydown or keyup, then nothing happens. What is the correct way to simulate the user pressing a special key like $ then? Also, I'm on Mac/Chrome if it matters

  • Can you achieve the desired result by using the input event instead of the keypress event? – Amila Jul 02 '23 at 18:33
  • @Amila Unfortunately I can't, I'm dealing with a canvas element and the [input event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) doesn't have support for canvas elements – Viktor Basharkevich Jul 02 '23 at 20:29
  • 1
    Logging a native `keypress` event when `$` gets entered (so when shift and 4 are pressed), gives me a `keyCode: 36`, why is it `52` in your code? – CBroe Jul 03 '23 at 08:33
  • @CBroe using [this tool](https://www.toptal.com/developers/keycode), it shows `$` as having a keyCode of `52`, and that `Home` has a keyCode of `36`. However, I just tried it again with also specifying `code`, `key` and `shiftKey`, and `$` gets pressed! Thank you for solving my question! – Viktor Basharkevich Jul 04 '23 at 17:43

0 Answers0