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).
@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.
3 thoughts on “Executing javascript in selenium webdriver to get page title with example”
Nice so we have 2 ways to get title 1) Javascript (document.title) 2) selenium (drv.getTitle())
We can also get title with below simple steps :
String title = driver.getTitle();
System.out.println("Title for page is : " +title);
JavascriptExecutor js= (JavascriptExecutor)driver;
//Title of page
JavascriptExecutor js= (JavascriptExecutor)driver;
String pagetitle=js.executeScript("return document.title").toString();
System.out.println("My Page Title Is : "+pagetitle);