0

Note: This question is not asking about how to obtain the character from a keyEvent.

Suppose there is a <input type="text"/> element, and a series of keyEvents fired on that element. These events can be triggered by any keys, including characters, arrows and backspaces. This results in a string which can be obtained via the value property of that input element. Now the question is, how to obtain this string without the input element?

The reason why the input element can't be directly used is because these events are already fired on a focused element. I tried to create an input element and use dispatchEvent() to reproduce the effect, but this doesn't work due to the reason described here. String.fromCharCode() also won't work as the effect of arrow keys and backspaces will not be reproduced.

SdtElectronics
  • 566
  • 4
  • 8

1 Answers1

0

I don't know of any browser API for doing this, and implementing it yourself is likely not a good idea. This is because editing text is extremely complicated, so simulating edits based on key inputs would almost certainly diverge from native <input> behavior. Some concerns to consider are:

  • Should tabs be captured?
  • What happens if arrow keys are pressed? How about shift + arrows?
  • If the user pastes using the context menu or a keybind, what should happen?

Of course, there are text editing components that do implement this themselves. Some that come to mind are CodeMirror and Tiptap. But those all try to display a cursor or provide some other visual feedback, and are fairly complicated.

BrownieInMotion
  • 1,162
  • 6
  • 11