Ruan Mendes
Ruan Mendes

Reputation: 92274

How to synthesize key presses in Javascript

I would like to write some tests for some input filtering code in a text box. For most tests, I can just call setValue and trigger the change event, which is easy to do. However, in this case, because I want to test that the input gets filtered out (or not), I can't just setValue() directly.

I tried dispatching keydown, keyup, keypress, textinput events. I can see that the handlers for them are being called, but the text doesn't actually show in the text box Note that this only "works" in Firefox, I understand the code would look different for other browsers.

function dispatch(target, eventType, charCode) {
   var evt = document.createEvent("KeyboardEvent");
   evt.initKeyEvent(
     eventType,
     true,
     true,
     window,
     false,
     false,
     false,
     false,
     charCode,
     0
   );
   target.dispatchEvent(evt);
}


var id = document.getElementById('id');
id.onkeydown = id.onkeyup = id.onkeypress = function() {console.log(arguments)}

dispatch(id, 'keydown', 65);
dispatch(id, 'keyup', 65);
dispatch(id, 'keypress', 65);
dispatch(id, 'textinput', 65);
// I can see the handlers were called but it doesn't display in the text box

I understand this has restrictions because we don't want web apps to just pretend like they are acting for the user. However, this is for testing my own application and I could launch Firefox with a specific profile and install plugins, or even write my own if I know it will help.

What I am after is to avoid using Selenium, I want to keep Java out of my JS tests because not only is it slow, but I have to re-implement a lot of the DOM querying in Java.

After all this, the question is, does anybody know how to get that code to actually modify the input? Tweaking settings, installing plugins?

List of questions that don't answer my question

Upvotes: 9

Views: 1933

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

I just found out that the following code does work in Chrome at least. No go in firefox or IE http://jsfiddle.net/D2s5T/14/

function dispatch(target, eventType, char) {
   var evt = document.createEvent("TextEvent");    
   evt.initTextEvent (eventType, true, true, window, char, 0, "en-US");
   target.focus();
   target.dispatchEvent(evt);
}
dispatch(el, "textInput", "a");

Upvotes: 1

Related Questions