Getting the return value of Javascript code in Selenium.

We can get the return value of Javascript code with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method.

We shall be returning the value from the Javascript code with the help of the keyword return. Also we have to add the statement import org.openqa.selenium.JavascriptExecutor to work with Javascript.


JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.getElementsByName('txtSearchText')[0].value")

Let us obtain the value entered in the edit box. The output should be Selenium.


Code Implementation

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavascriptValue{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "";
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element and enter text
      WebElement t=driver.findElement("txtSearchText"));
      // Javascript executor to return value
      JavascriptExecutor j = (JavascriptExecutor) driver;
      String s = (String) j.executeScript("return document.getElementsByName('txtSearchText')[0].value");
      System.out.print("Value is: " +s);


Updated on: 26-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started