We can fire JavaScript events in Selenium webdriver. Selenium can execute JavaScript events with the help of the JavaScript Executor. We shall pass the JavaScript commands as a parameter to the executeScript method.
We shall fire the JavaScript event of clicking an element. First of all, we shall identify the element with the help of any of the locators like xpath, css, link text, and so on.
We shall then pass argument [0].click() and webelement that shall be clicked as parameters to the executeScript method.
WebElement m = driver.findElement(By.linkText("Write for us")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", m);
Let us make try to click on the highlighted link −
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; public class FireEvntClickJs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify link WebElement m = driver.findElement(By.linkText("Write for us")); //Javascript Executor JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("arguments[0].click();", m); System.out.println("Page title after click: " + driver.getTitle()); driver.quit(); } }