How to input text in the text box without calling the sendKeys() using Selenium java?
Last Updated :
23 Sep, 2024
When automating web applications using Selenium WebDriver, the standard approach to input text into a text box is by using the sendKeys()
method. However, there are scenarios where you might want to input text without calling sendKeys()
. This can be achieved using JavaScriptExecutor in Selenium. JavaScriptExecutor allows direct manipulation of the DOM, providing more flexibility in controlling elements on a web page, especially when sendKeys()
might not work due to specific conditions or dynamic elements.
JavaScript Executor
JavaScript Executor allows you to run JavaScript code within the browser context. This method directly interacts with the web page's DOM, allowing you to set the value of an input field without simulating keystrokes.
Syntax
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement textBox = driver.findElement(By.className("HomePageSearchContainer_homePageSearchContainer_container_input__1LS0r"));
js.executeScript("arguments[0].value='Selenium';", textBox);
Example to input text in the text box without calling the sendKeys() using Selenium java
Java
package seleniumpractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import org.openqa.selenium.JavascriptExecutor;
public class JsEnterText {
public static void main(String[] args) {
// Set the path for the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Replace with your local path
// Initialize ChromeDriver
WebDriver driver = new ChromeDriver();
// URL launch
driver.get("https://www.geeksforgeeks.org/");
// Explicit wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// JavaScript Executor to enter text
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement textBox = driver.findElement(By.className("HomePageSearchContainer_homePageSearchContainer_container_input__1LS0r"));
js.executeScript("arguments[0].value='Selenium';", textBox);
// Verify value
String value = textBox.getAttribute("value");
System.out.println("Value entered is: " + value);
// Cleanup
driver.quit();
}
}
Explation
1. Import statements
- Imports statement include classes from , WebDriverManager, and Java's Duration class, which are necessary for interacting with the browser and manipulating web elements.
2. Class Declaration
public class JsEnterText
- The class JsEnterText contains the main method where the script execution starts.
3. Main Method
- Main method is the entry point of the program. where its executes.
4. WebDriver Setup
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
- WebDriverManager automatically manages the ChromeDriver binary.
- ChromeDriver initializes a new Chrome browser instance.
5. Navigate to URL
driver.get("https://www.geeksforgeeks.org/");
- Opens the specified URL in the browser.
6. WebDriverWait (Explicit Wait):
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
- Initializes an explicit wait with a timeout of 10 seconds. However, in this particular scripts, wait is not used further. it's prepared to handle waits if needed, but in this case, you directly find the element and execute JavaScript.
7. JavaScript Executor:
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement textBox = driver.findElement(By.id("mobile-search-strings"));
WebElement textBox = driver.findElement(By.className("HomePageSearchContainer_homePageSearchContainer_container_input__1LS0r"));
js.executeScript("arguments[0].value='Selenium';", textBox);
- Casts the driver to JavascriptExecutor, which allows running JavaScript commands.
- Locates the text box element by its className(("HomePageSearchContainer_homePageSearchContainer_container_input__1LS0r"));
- Uses JavaScript to set the value attribute of the text box to 'Selenium'.
8. Verify and Print Value:
String value = textBox.getAttribute("value");
System.out.println("Value entered is: " + value);
- Retrieves the value attribute from the box and prints it to the console. This should display the text that was set via JavaScript.
Output
OutputConclusion
In conclusion, while the sendKeys() method is a common approach to enter text in Selenium WebDriver, using JavaScriptExecutor offers an alternative and more flexible way of inputting text into web elements. By bypassing sendKeys()
, you can directly interact with the DOM, making it easier to handle complex or dynamic web pages. applying JavaScriptExecutor ensures your automation scripts are versatile and capable of handling different web application behaviors.
Similar Reads
How to select all Text in HTML Text Input when clicked using JavaScript? To select the text in HTML Text Input we can use the JavaScript DOM methods and we will select the text when we click the text box.Using document.getElementById() methodSyntax:<input onClick="this.select();" > or document.getElementById("ID").select();Example 1: We will use "this.select()" in
1 min read
How do I send a DELETE keystroke to a text field using Selenium with java? Sending a DELETE keystroke to a text field using Selenium with Java is a common task when automating web form inputs. Whether you're testing the behavior of input fields or simulating user actions, it's important to know how to interact with text fields effectively. Selenium provides a simple way to
3 min read
How to upload a file in Selenium java with no text box? Uploading a file in Selenium Java without a visible text box can be easily handled using the sendKeys() method. Even if the file input field is hidden or styled as a button, Selenium allows you to interact with it by providing the file path directly. This method simplifies the process of file upload
3 min read
How to simulate pressing enter in HTML text input with Selenium ? Selenium is an inbuilt module available in python that allows users to make automated suites and tests. We can build code or scripts to perform tasks automatically in a web browser using selenium. Selenium is used to test the software by automation. Also, programmers can create automated test cases
3 min read
Working with Input box/Test Box in Selenium with Python Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python.Working with Input box/Test Box, let us h
1 min read
How to get text from the alert box in java Selenium Webdriver? In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert
2 min read
How to clear all content in html text box using Selenium? Selenium is one of the most popular tools out there when it comes to automating web applications. Selenium is widely used for automating user interactions like filling out the forms, clicking on buttons, or navigating to a page. Selenium provides a programmable interface where users can write automa
5 min read
Click the Button by Text Using java and Selenium One common action testers need to perform is to click buttons by text using Java and Selenium. This method is particularly useful when buttons lack unique identifiers like IDs or classes. By applying Selenium powerful locators, you can easily locate buttons based on their displayed text, ensuring yo
3 min read
How to click the 'Ok' button inside an alert window with a Java Selenium command? An alert window is a pop-up box shown over the webpage to convey error messages using the alert() function of JavaScript. It has only one button "OK" which the user must press to continue browsing the webpage. A person might automate the website testing process and stumble upon pages that display al
3 min read
How to extract text from a web page using Selenium java and save it as a text file? Extracting text from a web page using Selenium in Java is a common requirement in web automation and scraping tasks. Selenium, a popular browser automation tool, allows developers to interact with web elements and retrieve data from a webpage. In this article, we will explore how to extract text fro
3 min read