Delivered by FeedBurner

Executing javascript in selenium webdriver to get page title with example

JavascriptExecutor is very useful Interface in webdriver software testing tool. Interface JavascriptExecutor helps you to execute javascript in your software test case whenever required. If you knows/remember, We had seen Different examples of executing javascript in selenium IDE to perform different actions. Let me give you one example of executing javascript in selenium WebDriver software testing tool.

Sometimes in your test case, you needs to store your software web application page title to compare it with expected page title. In selenium IDE, we can use "storeTitle" command to store it in variable. In webdriver ,we can do it directly using driver.getTitle(); as shown in this example. But if you wants to do it using javascript then how will you do it?

Example : Get page title using javascript in selenium webdriver

Copy bellow given @Test method part of get page title 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).
 public void test () 
  JavascriptExecutor javascript = (JavascriptExecutor) driver;
  //Get current page title
  String pagetitle=(String)javascript.executeScript("return document.title");  
  System.out.println("My Page Title Is  : "+pagetitle);
  //Get current page URL
  String CurrentURL = driver.getCurrentUrl();
  System.out.println("My Current URL Is  : "+CurrentURL);

(View more JavascriptExecutor examples in webdriver)

In above example, I have used JavascriptExecutor to execute java script in selenium webdriver software testing tool. Inner javascript will return current page title and store it in variable = pagetitle. Then Next statement will print it in the console. You can use that variable value to compare with your expected page title if required.

Last 2 syntax will get current page URLs and Print it in console.

1 comment:

  1. Nice so we have 2 ways to get title 1) Javascript (document.title) 2) selenium (drv.getTitle())