简体   繁体   中英

How to simulate keyboard press “full stack” with JS?

I've read and tried the solutions for this question but none of them work as I expect.

In the code snippet below I register two event listeners and see both callbacks fire as a response to the keydown event on the input and document .

However, my expectation is that when this line of code runs there's an additional text entered into the input, a .

input.dispatchEvent(keyEvent);

In other words, I expect that invoking dispatchEvent on the input element with KeyboardEvent as an argument should add text to the input, however it does not .

It does invoke the callbacks registered with the eventListener.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input id="input">

  <script>
    const input = document.getElementById('input')

    input.addEventListener('keydown', (e) => {
      console.log('Keydown on Input: ', e.key)
    })
    document.addEventListener('keydown', (e) => {
      console.log('Keydown on Doc: ', e.key)
    })

    function focusInputThenFireEventKeyboardEvents() {
      input.value = 'I want '
      input.focus()
      input.dispatchEvent(new Event('focus'));
      input.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
      input.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
      var keyEvent = new KeyboardEvent("keydown", { key: "a", char: "a", shiftKey: true });
      var keyEvent2 = new KeyboardEvent("keydown", { key: "d", char: "d", shiftKey: true });
      input.dispatchEvent(keyEvent);
      document.dispatchEvent(keyEvent2);
    }
    setTimeout(focusInputThenFireEventKeyboardEvents, 500)
  </script>
</body>

</html>

在此处输入图像描述

You can check documentation here - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent which says that keyboard event indicates user's interaction with key on keyboard and in order to handle text input you need to use input event. Even if you dispatch an event like const input.dispatchEvent(new Event("input", {"bubbles":true, "cancelable":false})) it doesn't mean it will change the input but you can use it to programmatically set the value of input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM