Executing the JavaScript code

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.

  • By casting the WebDriver instance to a JavascriptExecutor interface, we can execute the JavaScript code in Selenium WebDriver:

JavascriptExecutor js = (JavascriptExecutor) driver;

  • a single line of JavaScript code is executed to return the title of the page.

String title = (String) js.executeScript("return document.title");

  • a multiline JavaScript code to retrieve the count of links on a page:

long links = (Long) js.executeScript("var links = document.getElementsByTagName('A'); return links.length");

To view or add a comment, sign in

More articles by Reza Roozbehani

  • Button

    Buttons can come in two forms - standard and submit buttons. Standard buttons are usually created by the ‘button’ tag…

  • Navigation - Visit pages within a site

    Browsers provide various navigation methods to access web pages from the browser history or by refreshing the current…

  • Performing double-click on an element

    There will be elements in a web application that need double-click events fired to perform some actions. For example…

  • Checking an element's state

    Many a time a test fails to click on an element or enter text in a field, as the element is disabled or exists in the…

  • Implicit Wait

    In Java, if we want to wait for something, we can use the sleep method on the Thread class. This causes the program to…

  • Narrowing down by locating within chained search Contexts

    You can combine search contexts together. For example, You have an element that is hard to find with a single locator.

  • Checking an element's presence

    The Selenium WebDriver does not implement Selenium RC's isElementPresent() method to check if an element is present on…

  • normalize-space(.) versus text(.)

    if you want to locate a paragraph of text which contains some styling:

    A paragraph with this text in…

Insights from the community

Others also viewed

Explore topics