
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
Fire JavaScript Event in Selenium
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.
Syntax
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 −
Example
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(); } }
Output
Advertisements