How to Handle ElementClickInterceptedException in Selenium Java
Tags: elementclickintercepted, selenium, javascript, automationtesting
Published: 2023-09-21 08:18:19

Selenium is one of the most popular automation testing frameworks organizations use to automate their websites. With [Selenium’s 4.0.0](https://www.lambdatest.com/blog/what-is-deprecated-in-selenium4/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) release, multiple breaking changes have been introduced, like WC standardization, Selenium Manager, Chrome DevTools, etc.

With all these features, it has made the test automation engineer’s life easy by removing the complexities like adding executable driver’s path for browser drivers, [browser compatibility issues](https://www.lambdatest.com/blog/css-browser-compatibility-issues/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog), etc., and helping them to write the automated tests faster and more comfortably.

When it comes to test automation, automation engineers (count me in too :)) often struggle through a common problem, i.e., getting exceptions when running the tests. There are different [exceptions in Selenium](https://www.lambdatest.com/blog/49-common-selenium-exceptions-automation-testing/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) that test (or automation) engineers come across when performing test automation. Some common exceptions are [NoSuchElementException](https://www.lambdatest.com/automation-testing-advisor/selenium/classes/org.openqa.selenium.NoSuchElementException), *TimeoutException, SessionNotCreatedException, StaleElementReferenceException, ElementClickInterceptedException, etc*.

In this [Selenium Java tutorial](https://www.lambdatest.com/learning-hub/selenium-java?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub), we will discuss the nitty-gritty of *ElementClickInterceptedException* in Selenium and ways to mitigate the exception.

So, let’s get started.

***In this*** [***flutter automation testing tools***](https://www.lambdatest.com/blog/flutter-testing/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) ***tutorial, we will discuss how to test flutter apps manually and automation on real device cloud***

### What is an ElementClickInterceptedException?

*ElementClickInterceptedException* occurs when the click command cannot be executed on the WebElement as it is not clickable. This exception typically occurs when another WebElement overlaps the WebElement that somehow receives the click.

As we use the Java programming language in this blog, the exception name *ElementClickInterceptedException* is used here. It might change in the case of other programming languages as below –

<table><tbody><tr><td colspan="1" rowspan="1"><p>PROGRAMMING LANGUAGE</p></td><td colspan="1" rowspan="1"><p>EXCEPTION NAME</p></td></tr><tr><td colspan="1" rowspan="1"><p>Java</p></td><td colspan="1" rowspan="1"><p>ElementClickInterceptedException</p></td></tr><tr><td colspan="1" rowspan="1"><p>C#</p></td><td colspan="1" rowspan="1"><p>OpenQA.Selenium.ElementClickInterceptedException</p></td></tr><tr><td colspan="1" rowspan="1"><p>Ruby</p></td><td colspan="1" rowspan="1"><p>ERROR: element click intercepted</p></td></tr><tr><td colspan="1" rowspan="1"><p>Python</p></td><td colspan="1" rowspan="1"><p>selenium.common.exceptions.ElementClickInterceptedException</p></td></tr><tr><td colspan="1" rowspan="1"><p>JavaScript</p></td><td colspan="1" rowspan="1"><p>WebDriverError: element click intercepted:</p></td></tr></tbody></table>

The following exception log is printed in the console when ElementClickInterceptedException is thrown using [Selenium with Java](https://www.lambdatest.com/blog/selenium-with-java/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog):

![image](https://cdn-images-1.medium.com/max/800/0*kXHt9o2m65Dggkj-.png)

The logs show that instead of the actual element on which the [click command](https://www.lambdatest.com/blog/perform-mouse-actions-in-selenium-webdriver/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) was called, it was not clickable as some other element covered it; hence, the exception was thrown.

Different reasons can cause the *ElementClickInterceptedException* in [Selenium](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage). Let’s learn about them in the next section.

***Mobile*** [***emulators online***](https://www.lambdatest.com/mobile-emulator-online?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) ***from LambdaTest allows you to seamlessly test your mobile applications, websites,and web apps on mobile browsers and mobile devices.***

### What are the causes of ElementClickInterceptedException?

The following are the major causes that can lead to *ElementClickInterceptedException* thrown by [Selenium WebDriver](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub):

* WebElements overlap each other
    
* WebElement is disabled
    
* WebElement is not visible or not available in the [DOM](https://www.lambdatest.com/blog/document-object-model/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) currently at the time when the click command was executed. This can happen due to a slow Internet connection, and the automation scripts are executed while the web page is not loaded.
    

Let’s discuss these causes in detail one by one.

### Cause 1: WebElements overlapping with each other

Overlapping elements on the webpage can cause problems in running test automation scripts. When interactions are done with such elements, we often receive different exceptions based on the interactions performed. However, if we try to click on the element, an *ElementClickInterceptedException* will be thrown.

Here is an example of the web page from the UITestingPlayground website that has the name field overlapped with some other WebElement.

![image](https://cdn-images-1.medium.com/max/800/0*loZwbGcob7hsKXnv.jpg)

So, ideally, to interact with the name field, we will have to scroll to get the name field into view and then perform the interaction on it to handle the *ElementClickInterceptedException* in Selenium.

### Cause 2: WebElement is disabled

Another reason for getting the *ElementClickInterceptedException* in Selenium is that the WebElement might be disabled, and Selenium may not be able to perform clicks as desired through the automation script.

This may happen in scenarios like filling up the user registration form on the website, where the Submit button remains disabled unless all the mandatory fields are filled up correctly. So, in case the Submit button is clicked while it is still disabled, Selenium WebDriver might throw an *ElementClickInterceptedException*.

### Cause 3: WebElement was not visible when the click command was executed

When the tests are executed using test automation scripts, web page load time should also be considered. As the automation scripts continue to execute line by line, once the first line is executed, the program moves to the next line.

Consider an example of an eCommerce website with multiple JavaScript codes running on the web page.

We locate a product and click the Add to Cart button next to it as a part of our test scenario. There is a higher chance of getting an *ElementClickInterceptedException* as the webpage is not completely loaded, and we are trying to click on a WebElement that is currently not visible in DOM.

Having learned about the causes for *ElementClickInterceptedException* in Selenium, let’s now proceed and check out the multiple ways to handle the exception and run our Selenium test automation scripts hassle-free.

### How to handle ElementClickInterceptedException in Selenium?

Before we write the test automation scripts, it would be good to share the details of the tools used in this blog to demo the solutions for handling the *ElementClickInterceptedException* in Selenium.

* Programming Language — Java 17
    
* Web Automation tool — Selenium WebDriver — version — 4.10.0
    
* Build Tool — [Maven](https://www.lambdatest.com/blog/getting-started-with-maven-for-selenium-testing)
    
* Test Runner — [TestNG](https://www.lambdatest.com/learning-hub/testng)
    
* Cloud Platform to run web automation tests — [LambdaTest](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage)
    

**Project Setup**

The Maven project has been created, and the respective dependencies for TestNG and Selenium WebDriver have been updated in the pom.xml. The build and plugins section in the pom.xml are updated with the *maven-sure-fire* and *maven-compiler* plugins to execute the tests using the command line interface. We will use different [test scenarios](https://www.lambdatest.com/learning-hub/test-scenario?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub) in this project to demo how to handle the *ElementClickInterceptedException* in Selenium.

```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>io.github.mfaisalkhatri</groupId>
<artifactId>selenium-exceptions-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>selenium-exceptions-demo</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<selenium.java.version>4.10.0</selenium.java.version>
<testng.version>7.8.0</testng.version>
<maven.compiler.version>3.11.0</maven.compiler.version>
<surefire-version>3.1.2</surefire-version>
<java.release.version>17</java.release.version>
<maven.source.encoding>UTF-8</maven.source.encoding>
<suite-xml>test-suite/testng.xml</suite-xml>
<argLine>-Dfile.encoding=UTF-8 -Xdebug -Xnoagent</argLine>

</properties>

<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.java.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<release>${java.release.version}</release>
<encoding>${maven.source.encoding}</encoding>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-version}</version>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value>
</property>
</properties>
<suiteXmlFiles>
<suiteXmlFile>${suite-xml}</suiteXmlFile>
</suiteXmlFiles>
<argLine>${argLine}</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
```

![image](https://cdn-images-1.medium.com/max/800/0*vYN0l7-PARwfyp7Y.png)

For better maintainability and re-using the page objects, the [Page Object Model (POM)](https://www.lambdatest.com/blog/selenium-java-testing-page-object-model/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) has been used in this project. It helps remove code duplication and separate the page objects from the tests, thus helping write cleaner automation tests.

In this section, we will be going through multiple solutions that can be used to handle the *ElementClickInterceptedException* in Selenium. We will use a couple of websites to demo the solution.

***Perform browser*** [***test automation***](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) ***on the most powerful cloud infrastructure. Leverage LambdaTest automation testing for faster, reliable and scalable experience on cloud.***

### Solution 1: Using Explicit Waits in Selenium WebDriver

Performing click action on the WebElement that did not get loaded properly on the web page is one of the causes that might lead to *ElementClickInterceptedException* in Selenium. To resolve this, we can use the [Explicit Waits in Selenium WebDriver](https://www.lambdatest.com/blog/selenium-webdriverwait/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog).

We can use the ExpectedConditions like *elementToBeClickable* to be sure that the WebElement we are clicking is clickable. We may also use the *invisibilityOfElementLocated* method. This comes in handy in case WebElements like notifications or snack bars overlap.

**Test Scenario**

1. Navigate to the OWASP Juice Shop website.
    
2. Open the Login Page.
    
3. Login to the website using valid credentials.
    
4. Perform assertion for successful login by checking that the Logout link is displayed.
    

![image](https://cdn-images-1.medium.com/max/800/0*2KHvtFxfoMLogjWN.png)

***Home Page of OWASP Juice Shop website***

![image](https://cdn-images-1.medium.com/max/800/0*IMC18qxCx3d6fnB6.png)

***Login Page of OWASP Juice Shop website***

In this scenario, when we try to click on the Login button on the login page after entering valid credentials, it throws *ElementClickInterceptedException* as the login button is overlapped by the language notification snack bar.

**Implementation**

In this scenario, we will first navigate to the Homepage of the OWASP Juice Shop website and close all the pop-up messages so we can smoothly run our automation tests.

Next, we need to locate and click on the Account link to open it and locate the Login link. We will be navigated to the Login Page by clicking the Login link.

The following is the code from the *HomePage* class.

```
public class HomePage {

private WebElement dismissBtn() {
return getDriver().findElement(By.cssSelector("button[aria-label=\"Close Welcome Banner\"]"));
}

public void closeBanner() {
dismissBtn().click();
}

private WebElement meWantItBtn() {
return getDriver().findElement(By.cssSelector("a[aria-label=\"dismiss cookie message\"]"));
}

public void closeCookieMessage() {
meWantItBtn().click();
}

protected WebElement accountLink() {
return getDriver().findElement(By.id("navbarAccount"));
}

private WebElement loginLink() {
return getDriver().findElement(By.id("navbarLoginButton"));
}

public LoginPage navigateToLoginPage() {
closeBanner();
closeCookieMessage();
accountLink().click();
loginLink().click();
return new LoginPage();
}

}
```

The following are two pop-up messages appearing on the website’s Home page that need to be handled first before moving ahead to the Login page. You can learn more about it through this blog on [handling pop-ups in Selenium](https://www.lambdatest.com/blog/handling-login-popup-in-selenium-webdriver-using-java/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog).

![image](https://cdn-images-1.medium.com/max/800/0*_2RgoOK0IQ8E7_Jl.png)

***Deep dive to learn about*** [***test automation***](https://www.lambdatest.com/learning-hub/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub)***, its uasage, types and also gain insights on how to get started with automated testing.***

Let’s search for the selectors of the Dismiss button in the DOM using Chrome browser’s Developer Tools.

![image](https://cdn-images-1.medium.com/max/800/0*6xSKU-S5uWBVW5ph.png)

Once we inspect the Dismiss button in the Developer Tools, it takes us to the HTML tag button where the label is “Close Welcome Banner”. We can use this as the Selector for locating the Dismiss button. You can learn more about different locator strategies through this tutorial on [locators in Selenium](https://www.lambdatest.com/learning-hub/selenium-locators).

We will be using the [CSS Selector](https://www.lambdatest.com/learning-hub/css-selectors?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub) locator strategy to locate the Dismiss button, and the Selector will be *“button\[aria-label=”CloseWelcome Banner”\]”*. Similarly, we can use the Developer Tools window to find other WebElements on this website; we can use the Developer Tools window.

To handle the first popup, i.e., Welcome pop-up, the *dismissBtn(*) method is created in the *HomePage* class that locates the Dismiss button. The *closeBanner()* method clicks on the Dismiss button.

![image](https://cdn-images-1.medium.com/max/800/0*gaM7p3lvqmkowemt.png)

To handle the next pop-up displayed on the screen’s right-hand corner, the *meWantItBtn()* method is created in the *HomePage* class that locates the Me *Want it*! button, and the *closeCookieMessage()* method clicks on Me *Want it!* button.

![image](https://cdn-images-1.medium.com/max/800/0*pFGPpQ_W13OKFAlg.png)

Next, we move to the Account Link, open it, and click the Login link to navigate to the Login page. The *accountLink()* and *loginLink()* methods locate the WebElements for Account Link and Login Link.

![image](https://cdn-images-1.medium.com/max/800/0*qCUpFXGgwQ5S6QvN.png)

![image](https://cdn-images-1.medium.com/max/800/0*YjmB6ENDzWKi9dPJ.png)

The *navigateToLoginPage()* method performs the actions for closing the banner. The cookie message clicks on the Account and Login links and finally returns a new instance of the *LoginPage* class.

![image](https://cdn-images-1.medium.com/max/800/0*YNcEBYirHVQUbH-n.png)

On the Login page, as the language notification snackbar is displayed that overlaps the Login button, we need to wait for the notification to disappear so we can move ahead and click on the button and avoid the *ElementClickInterceptedException*.

The following code is from the *LoginPage* class that handles the login actions.

```
public class LoginPage {

private final HomePage homePage;

public LoginPage() {
this.homePage = new HomePage();
}

private WebElement emailField() {
return getDriver().findElement(By.id("email"));
}

private WebElement passwordField() {
return getDriver().findElement(By.id("password"));
}

private WebElement loginBtn() {
return getDriver().findElement(By.id("loginButton"));
}

private void waitForSnackBarToDisappear() {
final WebDriverWait wait = new WebDriverWait(getDriver(), Duration.ofSeconds(10));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".mat-simple-snack-bar-content")));
}

public ProductPage login(final String email, final String password) {
emailField().sendKeys(email);
passwordField().sendKeys(password);
clickLoginBtn();
return new ProductPage();
}

public boolean checkLogoutLinkIsDisplayed() {
openAccountMenu();
return getDriver().findElement(By.id("navbarLogoutButton")).isDisplayed();
}

public void openAccountMenu () {
this.homePage.accountLink().click();
}

public void clickLoginBtn() {
waitForSnackBarToDisappear();
loginBtn().click();
}
}
```

The *invisibilityOfElementLocated()* method from the *ExpectedConditions* class is used here to wait till the time the WebElement for the snackbar notification disappears so we can click on the Login button.

The *waitForSnackBarToDisappear()* method implements the logic discussed.

![image](https://cdn-images-1.medium.com/max/800/0*vHnzwBOGvWBfMeuG.png)

***Which are the most wanted*** [***automation testing tools***](https://www.lambdatest.com/blog/automation-testing-tools/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) ***that have climbed the top of the ladder so far? Let's take a look***

This *waitForSnackBarToDisappear()* method is called before the Login button is clicked using the *clickLoginBtn()* method.

![image](https://cdn-images-1.medium.com/max/800/0*a1Zep8OqH3GC7PDN.png)

Finally, the *login()* method is created to perform actions of entering values in email and password fields and clicking on the Login button.

Let’s write the test now and check out the actual working of the scenario. Here is the test method that is available in the *JuiceShopTests* class.

```
private ProductPage productPage;

@Test
public void testLogin() {
getDriver().get("https://juice-shop.herokuapp.com/#/");
final var loginPage = new HomePage().navigateToLoginPage();
this.productPage = loginPage.login("demo+1@gmail.com", "Juice@1234");
assertTrue(loginPage.checkLogoutLinkIsDisplayed());
}
```

In this test, we perform the steps to navigate to the OWASP Juice Shop website and call the *navigateToLoginPage()* method that will open the Login page after which the *login()* method will be called that has valid credentials as the parameters to login into the website.

Finally, the assertion is performed to check that the Logout link is displayed; this completes the login test.

**Test Execution**

To run the test, right-click on the testng.xml and select the option `Run …/testng.xml`*.*  
Below is the screenshot from the testng.xml file.

![image](https://cdn-images-1.medium.com/max/800/0*TKwO2obX6dte0z-e.png)

Before executing the test, it’s a good idea to check the *ElementClickInterceptedException*. To do this, let’s temporarily disable the *waitForSnackBarToDisappear()* method within the *clickLoginBtn()* method.

![image](https://cdn-images-1.medium.com/max/800/0*x6INdyOV9icTi4uk.png)

Here is the test execution result that shows the *ElementClickInterceptedException* in Selenium was thrown, and the test failed.

![image](https://cdn-images-1.medium.com/max/800/0*aChyVpueH2gemrDn.png)

Now, let’s uncomment the *waitForSnackBarToDisappear()* method in the *clickLoginBtn()* method and rerun the test.

![image](https://cdn-images-1.medium.com/max/800/0*-yC4bEWVyS1Y1u5A.png)

*ElementClickInterceptedException* in Selenium was handled successfully, and the tests passed.

![image](https://cdn-images-1.medium.com/max/800/0*jI7IM3wHYDaDusGy.png)

### Solution 2: Locate the overlay WebElement and click on it

The second solution we can try to handle the *ElementClickInterceptedException* in Selenium is locating the overlay WebElement and clicking on it. Then, perform the next steps to click on the required WebElement.

**Test Scenario**

1. Navigate to the OWASP Juice Shop website.
    
2. Login to the website.
    
3. From the product page, add a product to the cart.
    
4. Check that the cart shows “1” product added to it
    

![image](https://cdn-images-1.medium.com/max/800/0*mJqxmln4wf5nMZlr.png)

In this scenario, as soon as the product page is loaded after successful login, it is overlapped with an overlay screen that intercepts the click on the Add to Basket button on the page, and an *ElementClickInterceptedException* in Selenium is thrown.

***Which are the most wanted*** [***automation testing tools***](https://www.lambdatest.com/blog/automation-testing-tools/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) ***that have climbed the top of the ladder so far? Let's take a look***

**Implementation**

As we already discussed the login in Scenario 1, we will not be going into details for login again here. We will focus on the last 2 steps in this scenario: adding a product to the cart and checking that the cart shows “1” product added.

The following code is written in the *ProductPage* class that helps locate the WebElements and perform interactions on it.

```
public class ProductPage {

private WebElement appleJuiceAddToBasketBtn() {
return getDriver().findElement(By.cssSelector("mat-grid-tile:nth-child(1) &gt; div &gt; mat-card &gt; div:nth-child(2) &gt; button"));
}

private WebElement overlay() {
return getDriver().findElement(
By.cssSelector(".cdk-overlay-backdrop.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing"));
}
public void addAppleJuiceToCart() {
overlay().click();
appleJuiceAddToBasketBtn().click();
}

public String itemsInBasket() {
return getDriver().findElement(By.cssSelector("span.warn-notification")).getAttribute("innerText");
}
}
```

*overlay()* method locates and returns the WebElement for the overlay screen and is called in the *addAppleJuiceToCart()* method.

*itemsInBasket()* method returns the value of the items in the cart WebElement in the string format that will help us perform assertion.

Here is the test method *testAddProductToBasket()* available in the *JuiceShopTests* class.

We have already covered the login step in Scenario 1. This Scenario 2 test will run after the Scenario 1 test, and the test order will be handled in testng.xml.

```
@Test
public void testAddProductToBasket() {
this.productPage.addAppleJuiceToCart();
assertEquals(this.productPage.itemsInBasket(), "1 ");
}
```

**Test Execution**

Here is the screenshot of the testng.xml file that will be used to run the test.

![image](https://cdn-images-1.medium.com/max/800/0*DXaabeLyW8gWI0n8.png)

Before running the tests, let’s comment out the statement where we are locating the overlay screen and clicking on it to replicate the *ElementClickInterceptedException* in Selenium.

![image](https://cdn-images-1.medium.com/max/800/0*oLgFdNnsQ1bV_vrq.png)

The screenshot below shows the test execution result with the *ElementClickInterceptedException*.

![image](https://cdn-images-1.medium.com/max/800/0*mbzbyC3462kTcmZS.png)

If you check the logs closely, you will notice that it provides us with the WebElement locator for the overlay screen. This can be used directly to locate and click on the overlay screen WebElement.

![image](https://cdn-images-1.medium.com/max/800/0*IRxZJuVfYdBxLrcv.png)

Let’s uncomment the statement that clicks on the overlay WebElement and handles the *ElementClickInterceptedException* in Selenium.

![image](https://cdn-images-1.medium.com/max/800/0*17bW-mT3vAeTK0kl.png)

Let’s re-run the test and check the output.

![image](https://cdn-images-1.medium.com/max/800/0*dG8pX7XXisMKvZDc.png)

The tests passed successfully using the solution where we clicked the overlay screen before clicking the Add to Basket button.

Mobile [emulators online](https://www.lambdatest.com/mobile-emulator-online?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) from LambdaTest allows you to seamlessly test your mobile applications, websites,and web apps on mobile browsers and mobile devices.

### Solution 3: Clicking on the WebElement using JavaScriptExecutor

The third solution for handling the *ElementClickInterceptedException* in Selenium is using the *JavaScriptExecutor* to click on the WebElement. This is recommended in case the first two solutions don’t work. We can use this solution to directly click on the WebElement if we need a simple workaround.

**Test Scenario**

1. Navigate to [LambdaTest’s official website](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage).
    
2. Click and Play the video displayed on the right-hand side of the window.
    
3. To verify that the video was played successfully, check that the close button on the video player is displayed.
    

![image](https://cdn-images-1.medium.com/max/800/0*7IjjSS7i5jhqne7x.png)

![image](https://cdn-images-1.medium.com/max/800/0*_2n3JVPsOPV42D1F.png)

In this scenario, if we try to click on the video directly by clicking on it, it throws an *ElementClickInterceptedException*. So, we will be using the [*JavaScriptExecutor*](https://www.lambdatest.com/blog/how-to-use-javascriptexecutor-in-selenium-webdriver/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog) and handling it.

**Implementation**

The implementation of this scenario is quite easy. We will navigate to the Home page, locate the web element for the video, and click on it.

Finally, the assertion will be performed to check that the close button is displayed on the video player.

The below code is from the *HomePage* class created that takes care of the page objects and their respective interactions.

```
public class HomePage {

private WebElement videoLink() {
return getDriver().findElement(By.cssSelector("div > div:nth-child(1) > span > picture > img"));
}

public void clickOnVideoLink() {
videoLink().click();
}

public void clickOnVideoLinkUsingJSExecutor() {
final JavascriptExecutor executor = (JavascriptExecutor) getDriver();
executor.executeScript("arguments[0].click();", videoLink());
}

public WebElement videoCloseBtn() {
final WebDriverWait wait = new WebDriverWait(getDriver(), Duration.ofSeconds(20));
return wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".popup span.close")));
}

}
```

The *videoLink()* method locates the video link on the Home page. The *clickOnVideoLinkUsingJSExecutor()* method performs click on the link using *JavaScriptExecutor*, and the *clickOnVideoLink()* method uses the native click method to perform click on the video link.

*videoCloseBtn()* method returns the WebElement for Close button on the video player. This method will be further used in tests to write assertions to check that the button is displayed.  
The test code is written for testing the working of this scenario.

```
@Test
public void testHomePage() {
getDriver().get("https://www.lambdatest.com");
final HomePage homePage = new HomePage();
homePage.clickOnVideoLinkUsingJSExecutor();
assertTrue(homePage.videoCloseBtn().isDisplayed());
}
```

The test is straightforward; it will first navigate to the LambdaTest’s official website, click on the video link and perform an assertion to check that the close button is displayed.

**Test Execution**

The following test block in testng.xml will execute this scenario for us.

![image](https://cdn-images-1.medium.com/max/800/0*AdsAbk_ZyVVvTN7h.png)

Let’s first recreate the case where *ElementClickInterceptedException* in Selenium is thrown when the video is clicked on the Home page without using the *JavaScriptExecutor*.

We will comment on the statement that executes the script to click with *JavaScriptExecutor* and perform a normal click on the video.

![image](https://cdn-images-1.medium.com/max/800/0*PZt2noqMMmfHwhRK.png)

The following is the output of the test execution that shows that the *ElementClickInterceptedException* in Selenium was thrown while trying to click on the video.

![image](https://cdn-images-1.medium.com/max/800/0*EYTpH-na-PqvvEul.png)

Now, let’s replace the *homepage.clickOnVideoLink()* method with the *homePage.clickOnVideoLinkUsingJsExecutor()* and re-run the test.

![image](https://cdn-images-1.medium.com/max/800/0*58xQAz-XhpuyG5ea.png)

***In this*** [***Appium***](https://www.lambdatest.com/appium?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) ***tutorial, learn about Appium and its benefits for mobile automation testing. Take a look at how Appium works and see how to perform Appium testing of your mobile applications***

Using *JavaScriptExecutor*, the *ElementClickInterceptedException* in Selenium was handled successfully, and the tests passed.

![image](https://cdn-images-1.medium.com/max/800/0*2OTzS-TdPNfxxqMH.png)

### Solution 4: Scrolling into the View using JavaScriptExecutor before clicking on the WebElement

The fourth solution that can be used for handling the exception is scrolling into the view. Hence, the WebElement is visible on the window and can be clicked. Using this solution, we will first scroll the web page to the point where the element is clearly visible on the page and then perform a click on it.

This can be done using the *JavaScriptExecutor* only; the only change is the argument that we pass in the *executeScript()* method to execute the JavaScript. Here, we will be passing the *scrollIntoView()* argument.

**Test Scenario**

1. Navigate to the UITestingPlayground website’s Overlapped Element window.
    
2. Enter the value in the *Id* and *Name* fields.
    
3. Perform assertion by checking the value typed in the *Name* field.
    

![image](https://cdn-images-1.medium.com/max/800/0*WVAPwf5Yvo26989x.png)

*UITestingPlayground* website’s *Overlapped Element* window

In this website, the *Name* field is overlapped by another WebElement, so if we try to click to type some value in the field, it will throw an *ElementClickInterceptedException* in Selenium.

**Implementation**

In this scenario, we will navigate the UITestingPlayground website’s Overlapped Element web page. Next, we will scroll into view using *JavaScriptExecutor* and then type the value in the *Name* field.

Finally, assertion will be performed to check the value entered in the *Name* field.

The below code is available in the *OverLapElementPage* class.

```
public class OverLapElementPage {

private WebElement idField() {
return getDriver().findElement(By.id("id"));
}

private WebElement nameField() {
return getDriver().findElement(By.id("name"));
}

public void fillForm(final String id, final String name) {
idField().click();
idField().sendKeys(id);
final var executor = (JavascriptExecutor) getDriver();
executor.executeScript("arguments[0].scrollIntoView(true);", nameField());
nameField().click();
nameField().sendKeys(name);
}

public String textInNameField() {
return nameField().getAttribute("value");
}
}
```

The *idField()* and *nameField()* methods locate and return the WebElements for the *Id* and the *Name* fields, respectively. Using the *fillForm()* method, we can click on the *Id* and *Name* fields and type values in them. However, before we click on the *Name* field, we will use the *JavaScriptExecutor* to scroll into view.

The following line of code will help scroll to the web page to the point where the *Name* field is visible in the viewport.

![image](https://cdn-images-1.medium.com/max/800/0*TmnA7Tr3LdDQPjpN.png)

Below is the test written for this scenario. It is available in the *UITestingPlaygroundTests* class

```
public class UITestingPlaygroundTests extends BaseTest{

@Test
public void testOverLappingElement() {
getDriver().get("http://www.uitestingplayground.com/overlapped");

final var overLapElementPage = new OverLapElementPage();
final String id = "ID7763";
final String name = "Faisal K";
overLapElementPage.fillForm(id, name);

assertEquals(overLapElementPage.textInNameField(), name);

}
}
```

The first statement of code in the test navigates to the UITestingPlayground website’s Overlapped element page. Next, we call the *fillForm()* method from the *OverLapElementPage* class to fill values in the *Id* and *Name* fields.

Finally, assertion is performed to check the values typed in the *Name* field.

***Through this*** [***usability testing***](https://www.lambdatest.com/learning-hub/usability-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub) ***tutorial, you will learn how usability testing is a great way to discover unexpected bugs, find what is unnecessary or unused before going any further, and have unbiased opinions from an outsider***

**Test Execution**

The following test block is added in the testng.xml to execute the tests for this scenario.

![image](https://cdn-images-1.medium.com/max/800/0*R1iWZLWKxEzuOTK0.png)

Let’s first replicate the *ElementClickInterceptedException* thrown due to the *Name* field getting overlapped with another WebElement. To do so, we must comment out the *JavaScriptExecutor* statement in the *fillForm()* method.

![image](https://cdn-images-1.medium.com/max/800/0*PYRKOlU3F_jdUdfp.png)

On executing the test, the *ElementClickInterceptedException* in Selenium is thrown, as seen in the logs.

![image](https://cdn-images-1.medium.com/max/800/0*_DI_9A_2iZm5lJvE.png)

Let’s uncomment the *JavaScriptExecutor* statement in the *fillForm()* method and rerun the test.

![image](https://cdn-images-1.medium.com/max/800/0*X4UUM_ChoVaotbW_.png)

Using the *scrollintoView* argument in *JavaScriptExecutor* works perfectly fine handling the *ElementClickInterceptedException*, and the tests pass.

![image](https://cdn-images-1.medium.com/max/800/0*8f72bXj0l4iKcfQF.png)

### Solution 5: Using the Actions class of Selenium WebDriver

The next solution we will discuss for handling the *ElementClickInterceptedException* is using the [Selenium WebDriver’s *Actions* class](https://www.lambdatest.com/blog/what-is-actions-class-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog).

The primary reason for *ElementClickInterceptedException* in Selenium is that the respective element that needs to be clicked is either overlapped by another element or an overlay screen. So, using the Actions class’s *movetoElement()* method, we can move the focus to the required WebElement and then perform a click on it.

**Test Scenario**

1. Navigate to the [LambdaTest eCommerce](https://ecommerce-playground.lambdatest.io/) demo website.
    
2. On the Home page, open the Shop by Category side menu.
    
3. With the Shop by Category side menu open, click on the Blog main menu.
    
4. Verify the title of the Blog page.
    

![image](https://cdn-images-1.medium.com/max/800/0*n2mydNSCuKrWGOe8.png)

*LambdaTest eCommerce website demo page*

![image](https://cdn-images-1.medium.com/max/800/0*8c7n4NYhl82m5rzo.png)

*LambdaTest eCommerce website — Blogs menu*

In this scenario, after opening the Shop by Category side menu, when we try to click on the Blog main menu, it throws the *ElementClickInterceptedException* in Selenium. This exception is thrown as the Shop by Category menu overlaps the screen.

**Implementation**

In this scenario, we will first navigate to the LambdaTest eCommerce demo website and click on the Shop by Category side menu link. Once it opens, we will click on the Blogs menu.

The following code is available in the *MainPage* class.

```
public class MainPage {

private WebElement shopByCategoryLink() {
return getDriver().findElement(By.linkText("Shop by Category"));
}

public void openShopByCategoryMenu() {
shopByCategoryLink().click();
}

private WebElement menuBar() {
return getDriver().findElement(By.cssSelector(".entry-section div.navbar-collapse"));
}
private WebElement blogLink() {
return getDriver().findElement(By.linkText("Blog"));
}
public BlogPage navigateToBlogs() {
final Actions actions = new Actions(getDriver());
actions.moveToElement(menuBar()).click().build().perform();
blogLink().click();
return new BlogPage();
}
}
```

*shopByCateogryLink()* method locates and returns the WebElement for the menu link. *ShopByCategoryMenu()* method performs the click on the Shop by Category menu.

The *navigateToBlogs()* method will help in clicking the Blog menu. The *moveToElement()* method of the *Actions* class is used to move the focus to the menu bar so the overlay screen can be removed and we can click on the Blog menu link.

![image](https://cdn-images-1.medium.com/max/800/0*_bo_kgCmSf1a8Tnf.png)

To perform the assertion, we will be checking — “LATEST ARTICLES” in the page header on the Blog page.

![image](https://cdn-images-1.medium.com/max/800/0*KIxWJWdnXdSz9Pje.png)

The *BlogPage* class has been created to locate the WebElement for the page header.

```
public class BlogPage {

public String pageHeader () {
return getDriver().findElement(By.cssSelector(".entry-section div.mz-tab-listing-header h3")).getText();
}
}
```

The *pageHeader()* method locates the page header WebElement of a Blog page and returns its text in string format.

***This*** [***smoke testing***](https://www.lambdatest.com/learning-hub/smoke-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub) ***tutorial covers what smoke testing is, its importance, benefits, and how to perform it with real-time examples***

The following automated test in the [*LambdaTestEcommerceTest*](https://github.com/mfaisalkhatri/selenium-exceptions-demo/blob/main/src/test/java/io/github/mfaisalkhatri/tests/LambdaTestEcommerceTest.java) class will help check the scenario with assertion.

```
public class LambdaTestEcommerceTest extends BaseTest{

@Test
public void testNavigationToBlogsMenu() {
getDriver().get("https://ecommerce-playground.lambdatest.io/");
final var mainPage = new MainPage();
mainPage.openShopByCategoryMenu();
final var blogPage = mainPage.navigateToBlogs();
assertEquals(blogPage.pageHeader(), "LATEST ARTICLES");
}
}
```

The test is simple to understand. We first navigate to the LambdaTest eCommerce website, open the Shop by Category menu, and then navigate to the Blog page by clicking the Blog menu.

Finally, the assertion is performed to check that the page header is “LATEST ARTICLES”.

**Test Execution**

The following test block is added in the testng.xml to execute the tests for this scenario

![image](https://cdn-images-1.medium.com/max/800/0*q6XjekDwq7U1-LvM.png)

Let’s first try to execute the test by clicking on the Blog menu link directly without using the *Actions* class.

To do so, we will comment on the statements of code we wrote for using the *moveToElement()* method from *Actions* class, in the *navigateToBlogs()* method.

![image](https://cdn-images-1.medium.com/max/800/0*iVIVEwAuTESFfLTY.png)

Let’s run the test and check the output.

![image](https://cdn-images-1.medium.com/max/800/0*tGFRrTOFLo4rt7JF.png)

We can see the test failing after throwing an *ElementClickInterceptedException*.

Let’s re-run the test by uncommenting the *moveToElement()* method statement of the *Actions* class so it handles the *ElementClickInterceptedException* in Selenium.

![image](https://cdn-images-1.medium.com/max/800/0*zJCIJMMpQgCK5So6.png)

Here is the output of the test running successfully.

![image](https://cdn-images-1.medium.com/max/800/0*DTVruKfa4GZyl52q.png )

***A complete*** [***Manual testing***](https://www.lambdatest.com/learning-hub/manual-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub) ***tutorial covering all aspects of Manual testing, including strategies and best practices.***

### Solution 6: Setting custom resolution for the browser

The next solution is simple: maximizing the browser after we create the WebDriver instance. We can also set the custom window resolution for the browser in case we don’t want to run the tests by maximizing the browser window.

As per [Selenium Best Practices](https://www.lambdatest.com/blog/selenium-best-practices-for-web-testing/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=blog), it is advisable to maximize the window or use a custom window size that opens the window with wide mode for a uniform automation experience and to avoid elements overlapping issues related to *ElementClickInterceptedException*.

Going through all the previous solutions, it can be noted that ideally, the WebElements overlap or are not in the viewport. Hence, the *ElementClickInterceptedException* in Selenium is thrown while we try to click on the WebElement.

So, by maximizing or resizing the window to a custom resolution, we can get a better window view where all elements are ideally visible, locatable, and can be clicked easily.

**Maximizing the browser window**

The following line of code can be used to maximize the browser

![image](https://cdn-images-1.medium.com/max/800/0*LC4rAXA5sfHS5Ha4.png)

**Customizing the browser screen resolution**

There are two ways in which we can customize the resolution before we start running our automation tests.

* Customizing the window size by adding arguments using the *BrowserOptions* class
    
* Customizing the window size in a cloud grid like LambdaTest
    

**Resizing the browser window using Browser Options**

The respective class of browser options can be used to add arguments and resize the window. For example, we can resize the window of Chrome browser using the *ChromeOptions* class as follows:

```
private static void setupChromeDriver () {
final ChromeOptions options = new ChromeOptions ();
options.addArguments ("--no-sandbox");
options.addArguments ("--disable-dev-shm-usage");
options.addArguments ("--window-size=1050,650");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
}
```

The value for the screen resolution can be passed in the argument “*–window-size= &lt; resolution in x,y format &gt; ”:*

Likewise, the same arguments can be used with *FirefoxOptions* and *EdgeOptions* classes as well for resizing the window in Firefox and Edge browsers respectively.

**Resizing the browser window in LambdaTest Cloud Grid**

LambdaTest is an AI-powered test orchestration and execution that allows you to perform manual and [automation testing](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) on over 3000+ real browsers, devices, and platforms. It provides a reliable and scalable cloud grid to conduct [Java automation testing](https://www.lambdatest.com/java-automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) at scale.

For [Selenium Java testing](https://www.lambdatest.com/selenium-java-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage), it provides the [LambdaTest Capabilities Generator](https://www.lambdatest.com/capabilities-generator/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) website that helps set all the capabilities using GUI. The code can be copied and used in the test configuration and setup.

{% youtube SqQ8SugRDos %}

You can follow the [LambdaTest YouTube Channel](https://www.youtube.com/channel/UCCymWVaTozpEng_ep0mdUyw?sub_confirmation=1) and stay updated with the latest tutorials around [Selenium testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage), [Cypress testing](https://www.lambdatest.com/cypress-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage), CI/CD, and more.

To set the capabilities for screen resolution using the capabilities generator website, we need to click on *Configure Advanced Capabilities &gt;&gt;* Screen Resolution and select the desired screen resolution as required.

Once we select the resolution, the code is autogenerated and can be copied and pasted into the test automation scripts.

![image](https://cdn-images-1.medium.com/max/800/0*gQDgerpxPetEcPiR.png)

These capabilities are set in the *DriverManager* class in the *setupRemoteDriver()* method.

![image](https://cdn-images-1.medium.com/max/800/0*CWwM0IXpTEE3gWxs.png)

On executing the tests on the LambdaTest Cloud grid, we can check out the resolution details on the LambdaTest Automation Dashboard.

![image](https://cdn-images-1.medium.com/max/800/0*E90IL1yRHKZRFJmM.png)

### Solution 7: Using Thread.sleep() to debug the Exception

[*Thread.sleep()*](https://www.lambdatest.com/blog/sleep-java-method/?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=webpage) is a kind of hard wait hence, it is not a recommended solution to be used in the test automation. However, when required we can use the *Thread.sleep()* method to debug the issue to check if waiting for a certain amount of time does make the automation test work successfully and allows clicking on the WebElement.

If the WebElement is clickable ideally after applying *Thread.sleep()*, we may move to some of the ideal solutions that we discussed above.

### Which solution to choose for handling ElementClickInterceptedException?

We discussed around 7 solutions to help us handle the *ElementClickInterceptedException* in Selenium. We should try using the maximize window or setting it in custom size so it opens in wide mode. This can help handle the overlapping elements quickly.

If maximizing the window does not work, we can apply the *Explicit Wait* on the element, wait for the element to be clickable, and then perform a click on it.

Ideally, *JavaScriptExecutor* should work as an ideal solution using click or scroll to view arguments.

*Thread.sleep()* is not a recommended solution to be used. However, we can use it for debugging purposes.

***In this tutorial on*** [***Agile testing***](https://www.lambdatest.com/learning-hub/agile-testing?utm_source=devto&utm_medium=organic&utm_campaign=sept_21&utm_term=ap&utm_content=learning_hub)***, let's deep dive into the history of Agile testing, its advantages, disadvantages, methods, quadrants, and best practices.***

### Final Thoughts

The primary reason that may lead to the *ElementClickInterceptedException* in Selenium is that the WebElement required to be clicked may overlap with some other element. We discussed multiple solutions to handle this exception. The simplest solution we can try firsthand is to maximize the browser window or set a custom size that may make all the WebElements visible and interactable. However, if that still doesn’t work, we can try the other solutions discussed in this blog.

Happy Testing!