How to click using JavascriptExecutor in Selenium?

Category: Selenium WebDriver 21 0

People say, “Old is Gold”. They rightly said this because when all the general commands fail to perform its operation then JavascriptExecutor comes into the picture and clears the blockages. You know the initial release of Selenium was completely based on JavaScript. Today we are going to learn the click using JavascriptExecutor.

You may face some situations in Selenium where click operations do not go well. There could be many reasons; some of the reasons are listed below:

  • On –click method triggers JavaScript code
  • A clickable element is disabled

In this scenario, exceptions like, IllegalStateException, ElementNotVisibleException, StaleElementReferenceException and NoSuchElementException comes. This is the beauty of JavaScript that it has complete authority over the DOM hierarchy. We can execute any of the scripts using JavascriptExecutor which helps us to handle the adverse scenario of the Automation testing.

Recently, one of my friends had a problem in sending the text to the text box in Mozilla browser; however, the normal command was working fine in Chrome browser. He called me to seek help. I advised him to use JavaScript to send the text to Mozilla browser and believe me it worked. So we will later discuss this scenario in a separate post. Let’s discuss the scenario and command to click using JavascriptExecutor in Selenium Automation tool.

Before we proceed ahead I have some hot tutorials for you on Selenium Automation testing. Please have a look, it may benefit you a lot:

Awesome Articles for You

So these are really some awesome articles which you will love it definitely, It also increases your Selenium’s knowledge bank.

Let’s come back to our main topic. 🙂

click using javascriptexecutor in selenium

Performing click using JavascriptExecutor in Selenium Automation tool

Our approach to this scenario would be to first identify the type of exceptions which Selenium is sending to the console. This exception should come from the script from where this was getting failed. Once we identified the spot then further we have to handle the spot with JavaScript and we can do it by creating the instance of JavascriptExecutor.

Here is the basic and sample JavaScript command to click on the Web elements:

Let’s discuss this technique and following is the sample command for it.

Here is the entire program for performing click using JavascriptExecutor in Selenium Automation tool:

Related Articles

Add Comment