JavaScriptExecutor in Selenium WebDriver With Examples

JavaScriptExecutor in Selenium WebDriver:

In general, we do click on an element using click() method in Selenium.

For example:

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write separate script to execute JavaScript within the browser using Selenium WebDriver script. Just use predefined interface named ‘Java Script Executor’. We need to import the below package in the script.



Script – The JavaScript to execute
Arguments –
The arguments to the script(Optional). May be empty.
Returns –
One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

  • To type Text in Selenium WebDriver without using sendKeys() method

  • To click a Button in Selenium WebDriver using JavaScript

  • To handle Checkbox

  • To generate Alert Pop window in selenium

  • To refresh browser window using Javascript

  • To get innertext of the entire webpage in Selenium

  • To get the Title of our webpage

  • To get the domain

  • To get the URL of a webpage

  • To perform Scroll on application using  Selenium

See Also: How To Scroll Web Page Down Or UP Using Selenium WebDriver

  • To click on a SubMenu which is only visible on mouse hover on Menu

  • To navigate to different page using Javascript

  • To find hidden element in selenium using JavaScriptExecutor

Below program will guide you to handle some of the scenarios we do use in while writing scripts.

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.


Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Leave a Comment

Share via
Copy link
Powered by Social Snap