How to execute Javascript code using Selenium WebDriver?


  • Selenium WebDriver API provides the ability to execute JavaScript code with the browser window.
  • This is a very useful feature where tests need to interact with the page using JavaScript. Using this API, client-side JavaScript code can also be tested using Selenium WebDriver.
  • Selenium WebDriver provides a JavascriptExecutor interface that can be used to execute arbitrary JavaScript code within the context of the browser.
    • 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 displayed in the driver. TheJavascriptExecutor interface provides the executeScript() method to which we need to pass the JavaScript code.

                          String title = (String) js.executeScript(“return document.title”);

    While returning values from the JavaScript code, we need to use the return keyword. Based on the type of return value, we need to cast the executeScript() method. For decimal values, Double can be used, for non-decimal numeric values Long can be used, and for Boolean values Boolean can be used. If JavaScript code is returning an HTML element, then WebElement can be used. For text values, String can be used. If a list of objects is returned, then any of the values will work based on type of objects. Otherwise, a null will be returned.

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

                    long links = (Long) js.executeScript(“var links = document.getElementsByTagName(‘A’); return links.length”);

    • Arguments can also be a passed to the JavaScript code being executed by using the executeScript() method. In the following example, we want to set the value of an element. A special arguments array will be used inside the JavaScript code.

                                     js.executeScript(“document.getElementByID(‘name’).value = arguments[0]”,”John”);