-
Notifications
You must be signed in to change notification settings - Fork 14
Clicking Elements in Selenium using JavaScript
Selenium comes with a handy WebElement#click method that invokes a click event on a given element. But in some cases click action is not possible.
One example is if we want to click a disabled element. In that case, WebElement#click throws an IllegalStateException. Instead, we can use Selenium's JavaScript support.
To do this, the first thing that we'll need is the JavascriptExecutor. Since we are using the ChromeDriver implementation, we can simply cast it to what we need:
JavascriptExecutor executor = (JavascriptExecutor) driver;
After getting the JavascriptExecutor, we can use its executeScript method. The arguments are the script itself and an array of script parameters. In our case, we invoke the click method on the first argument:
executor.executeScript("arguments[0].click();", element);
Now, lets put it together into a single method that we'll call clickElement:
private void clickElement(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
}
WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".btn-search"));
clickElement(seeSearchResultsButton);
-
Nội dung khoá học kiểm thử tự động căn bản với Selenium và Java
-
Open browsers with selenium and java:
2.1. Edge
2.2. Headless browsers
2.3. Chrome mobile mode