char is deprecatedcharCode is deprecatedkey fires for both printable characters and control keyskeyCode is deprecatedwhich is deprecatedkeypress is deprecatedinput does not fire for elements that are not input, textarea, select or contenteditable - most annoyingly tabindex is not enoughIs 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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With