Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

Capture keys typed on android virtual keyboard using javascript

I have a web page with a textarea, and I need to capture the keys typed by the user (so that I can substitute different unicode characters for the keys typed). My current code is as follows:

$("#myTextArea").bind('keypress', function(event) {

    var keyInput = event.which;
   // call other functions

});

This above code works on PCs, and iPhone/Safari. However, it fails when using Chrome on an android (samsung) tablet. For some reason when I type on the android virtual (soft) keyboard, the "keypress" event is not triggered. The android version is 5.0.2.

If I try using "keyUp" or "keyDown", it always returns 229 for all characters (except for return key, space, backspace, etc).

Even though the keyCode is always 229, the textarea displays the correct characters typed by the user. Which means the device knows which key was entered, but somehow I'm unable to get a handle on this event (and the key code) using javascript.

Here are the alternatives that I have tried so far, and their outcomes:

$("#mainTextArea").on("keydown keyup", function(event) { 
    // event.which and event.keyCode both return 229

$(document).on('keypress', function(event) { 
    // function is not triggered

$('#myTextArea').bind('input keypress', function(event) { 
   // comes inside function, but keyCode and which are undefined

Any help regarding this issue is appreciated..

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately it seems you cannot do much here. Keypress event is deprecated, thus not fired. 229 on keyup and keydown indicates the keyboard buffer is busy. The reason - when you press a key - the input is still not guaranteed to be what the user pressed, because of auto suggest and other events that may follow immediately and invalidate the event. Although in my opinion it would have been better to send the key first, then fire another event perhaps on auto suggest so you can act upon it separately...

The only thing that I currently know of is to attach to both - keydown and keyup, store the value on keydown, get the value on keyup and find the delta, which is what user pressed. Unfortunately this will not work for non-input controls (e.g. - the body or something like that). Maybe not what you want to hear as answer but still.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...