5

I've used both

WebElement.sendKeys('') 

and

WebElement.setValue('')

In order to input text into fields. The vast majority of the time they seem to act the same, but I've found a few cases where setValue() works but sendKeys() does not.

All I can find in the Selenium docs is that sendKeys() 'more accurately imitates user input' then setValue(). Does anyone know what is actually happening under the hood?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
C. Peck
  • 3,641
  • 3
  • 19
  • 36

1 Answers1

1

sendKeys()

sendKeys() is the Java method from WebElement to simulate typing into an element, which may set its value.

  • Defination:

    void sendKeys(java.lang.CharSequence... keysToSend)
        Use this method to simulate typing into an element, which may set its value.
    
    Parameters:
        keysToSend - character sequence to send to the element
    
    Throws:
        java.lang.IllegalArgumentException - if keysToSend is null
    
  • Usage:

    driver.findElement(By.id("identifierId")).sendKeys("C.Peck@stackoverflow.com");
    

However there is no setValue() method in Java and the closest match seems to be setAttribute() JavaScript method.


setAttribute()

setAttribute() is the JavaScript method which sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

  • Syntax:

    Element.setAttribute(name, value);
    
  • Example:

    • HTML:

      <button>Hello World</button>
      
    • JavaScript:

      var b = document.querySelector("button"); 
      b.setAttribute("name", "helloButton");
      b.setAttribute("disabled", "");
      
  • Implementation through Java executeScript():

    ((JavascriptExecutor)driver).executeScript("document.getElementById('elementID').setAttribute('attribute_name', 'new_value_for_element')");
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352