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.
Syntax
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.
Example
Code Implementation
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class JavascriptValue{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/tutor_connect/index.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element and enter text WebElement t=driver.findElement(By.id("txtSearchText")); t.sendKeys("Selenium"); // 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); driver.quit(); } }