What is JavaScriptExecutor in Selenium

In this article we learn the what is JavaScriptExecutor in selenium webdriver and how to use JavaScriptExecutor in selenium webdriver with example.

What is JavaScriptExecutor in Selenium WebDriver?

JavaScript helps us to interact WebElement where Selenium fails to do so.

JavaScript (“JS” for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites.”

Sometimes we will find Selenium commands are not working properly.- JavaScript commands should be last resort if normal selenium commands are not working.

JavaScriptExecutor in Selenium Example:

Handling nested web elements. We have seen some toggle buttons, check boxes etc which are nested by some other tags like label etc. Normal selenium command “Click” will not be able to click on toggle sometimes, as it will find it is not clickable.

Complete area of some web elements like button, checkbox etc are not clickable. We need to click on specific part of element to perform action. Selenium might fail here sometimes. In this case also “Js” is very useful.

Scrolling is also a big problem in selenium. Using “Js”, we can scroll by pixels or to the web element.

Handling hidden elements. We can use “JS” to get text or attribute value from hidden web element which cannot be done by normal selenium methods.

Drag and drop issues can be handled using JS.

Selenium people provide an interface named “JavascriptExecutor “, which provides declaration of methods as below:

JavaScriptExecutor in Selenium Syntax:

JavascriptExecutor js=(JavascriptExecutor)driver;

Object executeScript (String arg0, Object… arg1); 

js. executeScript (“arguments [0]. click()”,ele);

Other Popular Articles

What is Actions Class in Selenium WebDriver?

Leave a Comment