
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use JavaScript in Selenium to Click an Element
We can use the JavaScript Executor in Selenium to click an element.
Selenium can execute JavaScript commands with the help of the method executeScript.
Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click. The parameters to be passed to the executeScript method to click an element are - arguments[0].click(); and the web element locator.
Syntax
WebElement m=driver.findElement(By.linkText("Company")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", m);
Let us click the link Company on the below page −
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ClickLnkJS{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement m = driver.findElement(By.linkText("Company")); // click with Javascript Executor JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", m); System.out.println("Page navigated to:" + driver.getTitle()); driver.quit(); } }
Output
Advertisements