The differences between type, keyPress and keyPressNative in Selenium

A friend asked me how to press the ENTER key in Selenium RC. A simple enough request? Just send the right JS key code? Well not quite - Selenium has issues with text input. For many forms where you need to just enter a few words, a date of birth or ZIP/Postal code, Selenium performs just fine. But if you need to enter text into a TextArea, and do things like: use the ENTER key - and type text character by character - Selenium gets a bit more flaky.

The issue stems from a bug in IE, where sending Javascript key press events does not necessarily mean IE will accept/display them. This affects the Selenium type_keys method. You can work around this by using type method. But this has its own drawbacks, such as not firing the appropriate keyboard events, or overwriting the existing contents of a field rather than appending.

There is a solution. Selenium 1.0 has another method of entering text, key_press_native. Key_press_native uses Java's UI Robot (java.awt.robot) to enter text into text input boxes and textareas. The 3 methods key_press_native, key_down_native and key_up_native are all you need to enter most characters. The downside is that the methods currently only accept Java Key Codes only, rather than regular strings.

So if you want to input into textarea two lines, such as "a\na", you should write code in java below:

selenium.type("name=notes", "a"); //input "a" into textarea with name "notes"
selenium.setCursorPosition("name=notes", "-1"); // you must set cursor before keyPressNative
selenium.keyPressNative(String.valueOf(KeyEvent.VK_ENTER)); // press enter
selenium.keyPressNative("65"); //press another "a"

你可能感兴趣的:(selenium)