- 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
How to get details of a webpage like url, title name, domain name etc using Javascript Executor in Selenium?
We can get details of a web page like url, title, domain name of webpage using JavaScript Executor in Selenium webdriver. Selenium can execute JavaScript commands with the help of the executeScript method. The command to be executed is passed as a parameter to that method.
Syntax
To get the page title,
JavascriptExecutor j = (JavascriptExecutor) driver; String s = j.executeScript("return document.title;").toString();
To get the current URL,
String p = j.executeScript("return document.URL;").toString();
To get the domain,
String d = j.executeScript("return document.domain;").toString();
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class JavaScrptScope{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/questions/index.php"); //JavaScript Executor JavascriptExecutor j = (JavascriptExecutor) driver; //To get the page title String s = j.executeScript("return document.title;").toString(); System.out.println("Title is: " + s); //To get the current URL String p = j.executeScript("return document.URL;").toString(); System.out.println("URL is: " + p); //To get the domain String d = j.executeScript("return document.domain;").toString(); System.out.println("Domain is: " + d); driver.close(); } }
Output
Advertisements