Executing the JavaScript code
The Selenium WebDriver API provides the ability to execute JavaScript code with the browser window. This is a very useful feature when tests need to interact with the page using JavaScript.
Selenium WebDriver provides a JavascriptExecutor interface that can be used to execute arbitrary JavaScript code within the context of the browser.
Let's create a test that will call JavaScript code to return title and count of links (that is a count of Anchor tags) from a page. Returning a page title can also be done by calling the driver.getTitle() method.
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title");
long links = (Long) js.executeScript("var links = document.getElementsByTagName('A'); return links.length");