Skip to content
Advertisement

Does there exist a cross-browser JavaScript library for simulating keyboard manipulation of an element?

I’m well aware of the standard event firing mechanisms for browsers, but I have a need for a JavaScript library that will simulate cursor and insertion point navigation via the keyboard. In particular, I need a library that will allow me to move the insertion point, but will also handle expanding or collapsing a selection range of text if, say, the virtual shift key is “pressed” while navigating with a virtual arrow key. Does such a cross-browser JavaScript library exist?

This is intended for use in a browser automation library, so suggestions of things like Selenium would be inappropriate. Furthermore, I would like to avoid libraries that have dependencies on large JavaScript frameworks like jQuery, if possible. Finally, this needs to be injectable within a page, so non-JavaScript solutions won’t work for my requirements.

Assuming I have an HTML page that looks something like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>keyboard</title>
</head>
<body>
  <input id="editor" value="hello world" />
</body>
</html>

I want to be able to call, in JavaScript, something like this:

function moveCursor() {
  var editor = document.getElementById("editor");
  editor.focus();

  // Hypothetical API here. This would need to be
  // adjusted to be used with the actual library.
  // Assume the pressKey() is defined as:
  //
  //   pressKey(element, keyCode, isShiftPressed)
  //
  keyboardSimulator.pressKey(editor, keys.END);
  keyboardSimulator.pressKey(editor, keys.LEFT, true);
  keyboardSimulator.pressKey(editor, keys.LEFT, true); 
}

After calling this JavaScript function, I would expect the focus in my page to be on the editor element, and for “ld” in the “hello world” value to be selected.

Advertisement

Answer

Actually there are libraries that do these things.

One of them is called Syn, and is included in bitovi FuncUnit:

http://funcunit.com

https://github.com/bitovi/syn

Advertisement