11

Is the recommended way going forwards to keep the list of predefined key values as a blacklist and assume what's not on there is a printable character? How's that going to work out for keyboards with special/programmable keys?

When trying to capture printable characters on non-input|textarea|select|contenteditable, is as of current the only non-hacky (no incomplete ranges or blacklists as seen in many similar questions) way without using deprecated features to use a hidden input/textarea and use its value for capturing characters that actually change that value?

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125

2 Answers2

4

Okay after looking into it for some time, the answer is: You can't determine this without relying on deprecated APIs or textarea hack.

Of course these are unlikely to ever go away, but if someone ends up looking for a way to do this without them, they won't find one.

A partial solution is a blacklist of the key values, but it's only a question of a new TV coming out with a quirky remote with extra proprietary keys or something like that and all bets are off.

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125
3

As a pragmatic solution use key:

Example code:

const isPrintableChar = e.key.length === 1 && e.key !== ' ';
const noModifier = !e.ctrlKey && !e.metaKey && !e.altKey;
return isPrintableChar && !noModifier;

For backward compatibility, consider using e.which as a fallback.

Community
  • 1
  • 1
Freddy
  • 402
  • 4
  • 8
  • 2
    Just checked, this does not work with emojis correctly. I'm keeping a blacklist generated based on the MDN page for now. – Tomáš Hübelbauer May 19 '17 at 11:23
  • 2
    +1 to the comment above. If the printable char is a Unicode astral (see https://mathiasbynens.be/notes/javascript-unicode ) then length > 1 but it should still print. Since a blacklist is bound to get outdated, seems like the best solution is using the old deprecated APIs. – CletusW Jul 11 '18 at 23:17