For a given WebClient, the focus can be on at most one element at any given time. Focus doesn't have to be on any element within the WebClient.

There are several ways to move the focus from one element to another. The simplest is to call HtmlPage.setFocusedElement(HtmlElement). This method will remove focus from whatever element currently has it, if any, and will set it to the new component. Along the way, it will fire off any "onfocus" and "onblur" handlers that have been defined.

  final HtmlInput userName = page.getHtmlElementById("userName");

The element currently owning the focus can be determined with a call to HtmlPage.getFocusedElement().

  HtmlElement elem = page.getFocusedElement();

Item traversal

To simulate keyboard navigation via the tab key, you can call HtmlPage.tabToNextElement() and HtmlPage.tabToPreviousElement() to cycle forward or backwards through the defined tab order. This tab order is defined by the tabindex attribute on the various elements as defined by the HTML specification. You can query the defined tab order with the method HtmlPage.getTabbableElements() which will return a list of all tabbable elements in defined tab order.

Finally, there is an assertion for testing that will verify that every tabbable element has a defined tabindex attribute. This is done with WebAssert.assertAllTabIndexAttributesSet(page).

Access keys

Access keys, often called keyboard mnemonics, can be simulated with the method HtmlPage.pressAccessKey(char).

Special keys

To use special keys, you can use htmlElement.type(int) with KeyboardEvent.DOM_VK_PAGE_DOWN.

To simulate typing while holding modifier keys (Shift/Ctrl/Alt) use the Keybord class.

Example: Simulate Ctrl+c to copy to the clipboard (details in the next section).

  final HtmlInput input = (HtmlInput) page.getElementById("i1");

  final Keyboard kb = new Keyboard();;


The clipboard interaction is disabled by default for the WebClient. This avoids side effect during testing and removes the need of having a running graphical subsystem (windows/X/xvfb).

To enable the clipboard support set a clipboard handle for the WebClient. HtmlUnit provides the AwtClipboardHandler the implements the interaction with your system/desktop clipboard.

  final ClipboardHandler clipboardHandler = new AwtClipboardHandler();

Attention:The provided AwtClipboardHandler does not work if you java vm runs in headless mode. In case you like to interact with the clipboard for the headless mode, please write a small impl of the ClipboardHandler yourself.

Usually you like to control the clipboard content from your test case.


Of course you can also implement your own ClipboardHandler to get full control.

To access the clipboard use the usual shortcuts.

  final Keyboard kb = new Keyboard();

  // select all;

  // copy;

  final Keyboard kb = new Keyboard();

  // paste;