How to input text in the text box without calling the sendKeys() using Selenium?

SeleniumAutomation TestingTesting Tools

We can input text in the text box without the method sendKeys with thehelp of the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method.

The JavaScript command to be run is passed as parameter to the method. To enter text we shall first identify the input box with the JavaScript method document.getElementById. Then we have to apply the value method on it.

Let us enter text Selenium in the below input box −

Syntax

JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsEnterText{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // JavaScript Executor to enter text
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      String s = l.getAttribute("value");
      System.out.println("Value entered is: " + s);
      driver.quit();
   }
}

Output

raja
Published on 03-Apr-2021 10:57:11
Advertisements