Book Image

Selenium Essentials

By : Prashanth Sams
Book Image

Selenium Essentials

By: Prashanth Sams

Overview of this book

Table of Contents (12 chapters)

The JavascriptExecutor class


JavascriptExecutor is a class under the Selenium library that executes JavaScript code snippets. For example, a Selenium WebDriver command such as WebElement.click() might not work on all browsers, but JavaScriptExecutor could help you to click on an element in any browser by executing the appropriate JavaScript snippet. There are a couple of Selenium WebDriver functions to handle JavaScript, such as executeAsyncScript() and executeScript(). The executeAsyncScript() method lets you inject JavaScript snippets into the page for asynchronous execution. The following is the syntax for this method:

JavascriptExecutor jse = (JavascriptExecutor)driver;

Let's see how you can click on an element without using Selenium's click() method. The following code snippet displays an alert message as a pop-up:

(JavascriptExecutor) driver).executeScript("arguments[0].click();", WebElement element);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("alert('Selenium...