- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reading JavaScript variables using Selenium WebDriver.
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
- Related Articles
- Find elements using Selenium WebDriver?
- Switch tabs using Selenium WebDriver with Java.
- How to Verify Tooltip using Selenium WebDriver?
- How to upload files using Selenium Webdriver?
- What is the best way to handle a Javascript popup using Selenium Webdriver?
- Selenium RC vs Selenium webdriver.
- Selenium WebDriver StaleElementReferenceException.
- Get page title with Selenium WebDriver using Java.
- Test if element is present using Selenium WebDriver?
- How to select checkboxes using selenium java webdriver?
- Delete Cookies On All Domains using Selenium Webdriver.
- How to deal with ModalDialog using selenium webdriver?
- Capturing browser logs with Selenium WebDriver using Java.
- How to click on across browsers using Selenium Webdriver?
- Test if an element is focused using Selenium Webdriver.

Advertisements