Alternate Way for sendKeys

JSEXECUTOR
One of my friend called me yesterday, he had an interview on Selenium WebDriver and got confused on 1 Question.

What is an alternative for sendKeys Method in WebDriver?

I also got stammered on this and thought in mind

Why the hell do we need this?

There are below possible reason that I could find, When we need any alternative to sendKeys.

  1. When the Text element is disabled or locked, sendKeys can not set the value in text field.
    (in my opinion, this is not the correct way of Automation, because the element is locked or disabled by intend to not allow any text insertion)
  2. When we want to write huge text as input… that time the way WebDriver work, by sending Series of characters from String one by one, and Which is Very time consuming. so to minimize that time we can use this alternate method

So now we have above two problems with sendKeys ……

Solution!!!

The best alternative I found is JavaScript

Way 1 to Execute Script

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
        myExecutor.executeScript("document.getElementsByName('q')[0].value='Kirtesh'");
        driver.quit();

in above example we have used javaScript to locate the Search Textbox and set the “Kirtesh” value in it.

lets look at another approach.

Way 2

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        WebElement searchbox = driver.findElement(By.xpath("//input[@name='q']"));
        JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
        myExecutor.executeScript("arguments[0].value='Kirtesh';", searchbox);
        driver.quit();

second example is very controlled approach, Here we are passing WebElement as a argument to the javaScript

There is still many more remained from JavascriptExecutor ……

Keep Exploring…

Keep Automating………………

Advertisements

2 thoughts on “Alternate Way for sendKeys

  1. Madhu June 6, 2017 / 10:24 am

    in the first example , 2nd argument ‘searchbox’.. we need to create it as a webelement or a string?

    Like

    • Kirtesh June 6, 2017 / 10:44 am

      Sorry but by mistake ‘searchbox’ kept in the method, it is not required at all in the first example, as we are getting the object in javascript only, I have corrected the code. Thank you!!!

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s