Why JavaScript execution handles edge cases in Selenium Java - Automation Benefits in Action
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.ElementClickInterceptedException; import java.time.Duration; public class JavaScriptExecutionEdgeCaseTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://example.com/testpage"); // Wait for button to be present WebElement button = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("overlappedButton"))); // Try standard click and expect failure boolean standardClickFailed = false; try { button.click(); } catch (ElementClickInterceptedException e) { standardClickFailed = true; } // Assert standard click failed if (!standardClickFailed) { throw new AssertionError("Standard click did not fail on overlapped button"); } // Use JavaScript to click the button JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", button); // Wait for result text to update WebElement result = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("resultText"))); // Assert result text is as expected String expectedText = "Button clicked!"; if (!result.getText().equals(expectedText)) { throw new AssertionError("Result text mismatch. Expected: '" + expectedText + "', but was: '" + result.getText() + "'"); } System.out.println("Test passed: JavaScript click handled edge case successfully."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to demonstrate why JavaScript execution handles edge cases better than standard Selenium clicks.
First, it navigates to the test page and waits for the button element that is overlapped by another element.
It tries a normal Selenium click on the button, which is expected to throw an ElementClickInterceptedException because the button is not clickable normally.
Then, it uses the JavascriptExecutor interface to run JavaScript code that clicks the button directly, bypassing the normal Selenium click restrictions.
After the JavaScript click, it waits for a result text element to appear or update, verifying that the click action succeeded.
Assertions check that the standard click fails and the JavaScript click succeeds, showing why JavaScript execution is useful for handling tricky edge cases like overlapped or hidden elements.
Now add data-driven testing with 3 different buttons that may be overlapped