0
0
Selenium Javatesting~15 mins

Clicking via JavaScript in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Click a button using JavaScript Executor in Selenium
Preconditions (3)
Step 1: Open the browser and navigate to the test page URL
Step 2: Locate the button element by its ID 'submitBtn'
Step 3: Use JavaScript Executor to click the button
Step 4: Verify that the button click triggered the expected action (e.g., URL changed to /success or confirmation message displayed)
✅ Expected Result: The button is clicked successfully via JavaScript, and the expected action occurs confirming the click.
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the button element is present before clicking
Verify the expected action after clicking (URL or page content change)
Best Practices:
Use explicit waits to ensure element is present and clickable
Use JavaScript Executor only when normal click() fails
Use By.id locator for button element
Handle exceptions gracefully
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Using driver.findElement without waiting for the element to be present
Using JavaScript click() without verifying the element is interactable
Hardcoding the path to chromedriver inside the code without flexibility
Not handling exceptions during click or navigation
Bonus Challenge

Now add data-driven testing with 3 different button IDs to click using JavaScript Executor

Show Hint