Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver - sendKeys() not sending all keys - Java

Tags:

java

selenium

I use Selenium Webdriver with Java and I've found a problem. When I try to send some text to the textfield, it only sends first char of two. I tried setting it with JavaScriptExecutor, but same thing happened. ChromeDriver is running and working fine. Code below:

    public void sendNumberToChrome (int number){
        textfield.clear(); //  textfield is already set, it's classic input field with max. 10 characters
        System.out.println(String.valueOf(number)); // This prints for example 94
        textfield.sendKeys(String.valueOf(number)); // But only "9" appears in the browser
    }

I also tried to send it character by character:

String[] arr = String.valueOf(number).split("(?<!^)");  // splits number character by character
for (String s : arr){
    System.out.println(s); // Prints 9 and then 4
    textfield.sendKeys(s); // Also only 9 appears
    Thread.sleep(100); // Maybe browser can not work too fast, so I will wait before sending next character
}

JavascriptExecutor also send only one character and every few minutes crashes (don't know why), so I am not using it. But what is interesting - when I do this:

textfield.sendKeys(String.valueOf(94));

It sends 94 to Chrome! I don't know where the problem is, can someone help me?

EDIT: Chrome version: 29.0.1547.76 m, Selenium Server Standalone 2.35.0, Chromedriver v2.3

like image 282
Manderius Avatar asked Jul 30 '26 05:07

Manderius


1 Answers

Javascript on the page is messing with your input

try this code

static boolean sendKeyIntoElement(WebElement webElement, String value){
    webElement.click();
    webElement.sendKeys(value);

    while(!webElement.getAttribute("value").equals(value)){
        webElement.click();
        webElement.sendKeys(Keys.CONTROL + "a");
        webElement.sendKeys(Keys.DELETE);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return webElement.getAttribute("value").equals(value);
}
like image 179
Ar maj Avatar answered Aug 01 '26 18:08

Ar maj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!