How to fire javascript event in Selenium?

SeleniumAutomation TestingTesting Tools

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.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class FireEvntClickJs{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();       driver.get("");
      // 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());


Updated on 02-Feb-2021 11:37:50