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.