Click a button using JavaScript Executor in Selenium
Preconditions (3)
✅ Expected Result: The button is clicked successfully via JavaScript, and the expected action occurs confirming the click.
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 java.time.Duration; public class ClickViaJavaScript { 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("submitBtn"))); // Use JavaScript Executor to click the button JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", button); // Wait for expected condition after click, e.g., URL contains 'success' boolean urlChanged = wait.until(ExpectedConditions.urlContains("success")); // Assertion if (urlChanged) { System.out.println("Test Passed: Button clicked via JavaScript and URL changed as expected."); } else { System.out.println("Test Failed: URL did not change after clicking button."); } } catch (Exception e) { System.out.println("Test Failed with exception: " + e.getMessage()); } finally { driver.quit(); } } }
This code opens a Chrome browser and navigates to the test page URL.
It waits explicitly for the button with ID 'submitBtn' to be present on the page.
Then it uses JavaScript Executor to click the button because sometimes Selenium's normal click() may not work if the element is hidden or overlapped.
After clicking, it waits for the URL to contain 'success' to confirm the click triggered the expected action.
Finally, it prints the test result and closes the browser.
Now add data-driven testing with 3 different button IDs to click using JavaScript Executor
click() method?click() may fail if element is hidden or overlapped.element in Selenium Java?JavascriptExecutor to use executeScript.executeScript with script arguments[0].click(); and the element passed as argument.WebElement button = driver.findElement(By.id("submitBtn"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", button);
System.out.println("Clicked");JavascriptExecutor js = driver;
js.executeScript("arguments[0].click();", button);JavascriptExecutor js = (JavascriptExecutor) driver;Pass the test and this pattern moves unknown