Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

How to set text in textarea quickly using Java and Selenium

This code work but sendKeys send all char one by one and is it very very long time (40s).

String value = "...very long text...";
WebElement element = ...
element.sendKeys(value);

How to set text in textarea quickly using Java and Selenium? either with an element of Selenium or by modifying the speed or the characters are sent one by one temorary.

Please no solution with javascript execution.

Upvotes: 1

Views: 2061

Answers (4)

Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

/!\ Caution, is it a workaround only.

String value = "...very long text...";
WebElement element = ...
String javascript = "arguments[0].value=arguments[1];";
(JavascriptExecutor) driver.executeScript(javascript, element, value.substring(0, value.length() - 1));
element.sendKeys(value.substring(value.length() - 1));

/!\ 2nd workaround (not work on remote):

String value = "...very long text..."; 
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(value), null);
WebElement element = ... 
element.sendKeys(Keys.CONTROL , "v");

Upvotes: 0

browsermator
browsermator

Reputation: 1354

Here's a way to use the clipboard for this:

    String value = "...very long text...";      
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable transferable = new StringSelection(value);
    clipboard.setContents(transferable, null);  
    wait = new WebDriverWait(driver, ec_Timeout);     
    WebElement element  = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("name_of_input_element")));
    String vKey = "v";

            try
            {
        element.sendKeys(Keys.CONTROL , vKey);    
            }
            catch (Exception ex)
            {

            }

Upvotes: 3

Greg Burghardt
Greg Burghardt

Reputation: 18783

The sendKeys method is the only pure Java way to enter text into a text field using Selenium. Unfortunately all other ways require JavaScript, which is something you do not want to do.

Your only other alternative is to contribute to the Selenium project on GitHub by submitting a pull request with the desired behavior, and convince the World Wide Web Consortium to include this new method (sendKeysQuickly?) in the official WebDriver spec: https://www.w3.org/TR/webdriver/ — not a small task indeed!

Upvotes: 2

Constantin Trepadus
Constantin Trepadus

Reputation: 503

you can set the value directly using js script:

  JavascriptExecutor js = (JavascriptExecutor) driver;
  js.executeScript("document.getElementById('textareaId').setAttribute('value', 'yourText')");

Upvotes: 0

Related Questions