Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly Simulating a User's Keypress In Javascript

A little bit of context: I'm working on a HTML5-based mobile app with an autocomplete feature that breaks on Android due to a bug in setSelectionRange: http://code.google.com/p/android/issues/detail?id=15245 Because of this, I can't directly manipulate the text in the text field as one normally would. To get around this issue, I was planning on manually firing several key events to simulate the user pressing keys on the android soft keyboard.

All of the solutions I've found in Is it possible to simulate key press events programmatically? and Firing a Keyboard Event in JavaScript merely fire the event without actually creating any text input.

Is there a way to simulate the entire keypress event, text input included, using javascript?

Update: fixed (sort of)

I got around this issue by using writing a plugin for Trigger (the wrapper we're using) that manually fires android keyboard events on the native level. It's hosted here: http://bit.ly/RiJqrM if anyone else is interested.

Yet Another Update:

Further frustration and subsequent testing led me full circle, and it turns out the above mentioned android bug may have been a bit of a red herring. The reason my caret behaved oddly is actually likely due to some combination of native android autocomplete and the fact that jQuery focus() doesn't work at all on android (shameless self promotion): Android JQuery focus() workaround

like image 243
Michael Marsh Avatar asked Oct 24 '12 20:10

Michael Marsh


1 Answers

No. Most browsers do not allow script to fully simulate a keypress: you can fire the event but the associated browser behaviour (updating the value of an input, editing the content of a contenteditable element, moving the caret, etc.) will not happen.

like image 101
Tim Down Avatar answered Oct 27 '22 07:10

Tim Down