Hello Folks,
It is asked in interviews sometimes about alternative of sendKeys() method in selenium webdriver. We will see the same thing here.
Javascript is the alternative for sendKeys method. First basic question why we would require alternative of sendKeys? You must have encountered some text box which is nested and selenium is not able to interact. Another place I find is selecting a date from calendar. Different applications use different types of calendar and it is difficult to create methods for each type of calendar. Javascript saves you here.
HTML web element has an attribute called “value” which stores the current value. If we type “Amod” in a First Name text box, “value” attribute of text box will be as “value=Amod”. Using javascript, we can directly set the value of “value” attribute.
Java Code:
Output:
If you want to learn how to select a date using Javascript, read below post.
How to select a date in calendar using Javascript.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium
i am not able to see any java code!!
Its there.
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TypeUsingJavascript {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,”./exefiles/chromedriver.exe”);
WebDriver driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get(“https://www.google.com/”);
WebElement searchBox= driver.findElement(By.name(“q”));
// Down casting driver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Setting value for “value” attribute
js.executeScript(“arguments[0].value=’selenium'”, searchBox);
}
}
where u set the webelemnt? how it identified the search box?
Check line no 19.