
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements