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

Updated on: 06-Apr-2021

643 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements