Determine if key press resulted in printable Unicode character being input without deprecated APIs

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?

Upvotes: 11

Views: 1386

Answers (2)

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.

Upvotes: 4

Freddy
Freddy

Reputation: 402

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.

Upvotes: 3

Related Questions