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
@Test
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.
Nice so we have 2 ways to get title 1) Javascript (document.title) 2) selenium (drv.getTitle())
ReplyDeleteWe can also get title with below simple steps :
ReplyDeleteString title = driver.getTitle();
System.out.println("Title for page is : " +title);
JavascriptExecutor js= (JavascriptExecutor)driver;
ReplyDelete//Title of page
JavascriptExecutor js= (JavascriptExecutor)driver;
String pagetitle=js.executeScript("return document.title").toString();
System.out.println("My Page Title Is : "+pagetitle);