Reading JavaScript variables using Selenium WebDriver.

SeleniumAutomation TestingTesting ToolsJavascript

We can read Javascript variables 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. 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.title")

Let us obtain the browser title of the below page by reading the value from Javascript variable. The output should be About Careers at Tutorials Point – Tutorialspoint.

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 JavascriptReadValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // Javascript executor to read value
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // get the browser title with document.title
      String t = (String)j.executeScript("return document.title");
      System.out.print("Current page title: " +t);
      driver.close();
   }
}

Output

raja
Published on 26-Oct-2020 10:57:26
Advertisements