Selenium WebDriver - Get Domain Name Using JavascriptExecutor

You need current software web application's page URL when you have to compare it with your expected URL. You can do it using WebDriver basic operation command driver.getCurrentUrl();. This method we have seen in my Previous Post. If you remember, we can use "storeLocation" command to get current software web application's page URL in selenium IDE software testing tool. Main purpose of this post is to explore how to get domain name in webdriver. So if you wants to store application's domain name then you need to use JavascriptExecutor in your software test case.

Look here, software application's domain name is different than the current page URL.

If my current page URL = http://only-testing-blog.blogspot.com/2013/11/new-test.html Then
My domain name is = only-testing-blog.blogspot.com

Let me provide you simple example of how to get current software web application's page URL using driver.getCurrentUrl(); and how to get domain name using JavascriptExecutor.

Example : Get current URL of page and domain name in selenium webdriver
Copy bellow given @Test method part of get current software web application's page URL using javascript example and replace it with the @Test method part of example given on THIS PAGE(Note : @Test method is marked with pink color in that linked page).


@Test
 public void test () 
 {  
  String CurrentURL = driver.getCurrentUrl();
  System.out.println("My Current URL Is  : "+CurrentURL);
  
  //Get and store domain name in variable
  JavascriptExecutor javascript = (JavascriptExecutor) driver;
  String DomainUsingJS=(String)javascript.executeScript("return document.domain");  
  System.out.println("My Current URL Is  : "+DomainUsingJS);
 }

(View more Javascript examples in selenium webdriver)

In above example, 1st 2 syntax will get and print current page URL. Last 3 syntax will get domain name using javascript and will print it in console.

7 comments:

  1. Can we get Domain Name without using Java script just like we get page title and current Url with the commands driver.getTitle(); and driver.getCurrentUrl();

    ReplyDelete
  2. You can get the domain without JavaScript by extracting it from the URL:
    URI uri = new URI(driver.getCurrentUrl());
    String domain = uri.getHost();
    (You may need to silence URISyntaxException)

    ReplyDelete
    Replies
    1. Thanks Ofer R thats an extra additional information

      Delete
  3. why "return document.domain" is written in the above code and what is its significance???

    String DomainUsingJS=(String)javascript.executeScript("return document.domain");

    ReplyDelete
  4. why "return document.domain" is written in the above code and what is its significance???

    String DomainUsingJS=(String)javascript.executeScript("return document.domain");

    ReplyDelete
  5. thanks for sharing with us it is really good information

    ReplyDelete