Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reading JavaScript variables using Selenium WebDriver.
We can read JavaScript variables with Selenium WebDriver using the executeScript method. This method allows Selenium to execute JavaScript commands directly in the browser and return their results. To work with JavaScript in Selenium, we need to import org.openqa.selenium.JavascriptExecutor.
Syntax
JavascriptExecutor j = (JavascriptExecutor) driver;
String result = (String) j.executeScript("return document.title");
Reading Document Properties
The most common use case is reading document properties like title, URL, or DOM elements. Let's obtain the browser title by reading the JavaScript variable document.title.
Example
Here's a complete example that reads the page title using JavaScript execution:
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
Current page title: About Careers at Tutorials Point - Tutorialspoint
Reading Custom JavaScript Variables
You can also read custom JavaScript variables defined on the page:
// Read a custom JavaScript variable
String customVar = (String) j.executeScript("return window.myCustomVariable");
// Read element properties
Long elementCount = (Long) j.executeScript("return document.getElementsByTagName('div').length");
// Read local storage
String storageValue = (String) j.executeScript("return localStorage.getItem('key')");
Key Points
- Always cast the return value to the appropriate data type
- Use
returnstatement in JavaScript to get values back - JavascriptExecutor can read any accessible JavaScript variable or property
- Useful for reading dynamic content, custom variables, or browser properties
Conclusion
Selenium's executeScript method provides powerful access to JavaScript variables and browser properties. Use it to read dynamic content, custom variables, or any JavaScript-accessible data during automated testing.
