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
How can we use JavaScript Executor to click and enter data to a web element in Selenium?
We can use JavaScript Executor to click and enter data to a web element in Selenium webdriver. Selenium can run JavaScript commands with the help of the executeScript method.
To click an element, the parameters to the executeScript method are - arguments[0].click(); and the webelement locator.
Syntax
WebElement l = driver.findElement(By.className("gsc-input"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);
Then to enter data to the edit box, the parameter passed to the executeScript method is – web element locator.value
Syntax
j.executeScript("document.getElementsByName('gsc-i-id1')[0].value= 'Java'");
Let us try to click on the below edit box and enter data into it.

Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavaScrptVal{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.google.com/");
WebElement l = driver.findElement(By.name("q"));
//JavaScript Executor to click element
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", l);
//JavaScript Executor to enter text j.executeScript("document.getElementsByName('q')[0].value= 'Java'");
String s = l.getAttribute("value");
System.out.println("Value entered is: " + p);
driver.close();
}
}
Output

Advertisements