Set value of input instead of sendKeys() - Selenium WebDriver nodejs
Asked Answered
H

9

67

I have a long string to test and sendKeys() takes too long. When I tried to set the value of the text the program crashes. I know the Selenium sendKeys() is the best way to test the actual user input, but for my application it takes too much time so I am trying to avoid it.

Is there a way to set the value right away?

See this quick example:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
      build();

driver.get('http://www.google.com');

// find the search input field on google.com
inputField = driver.findElement(webdriver.By.name('q'));

var longstring = "test"; // not really long for the sake of this quick example

// this works but is slow
inputField.sendKeys(longstring);

// no error but no values set
inputField.value = longstring;

// Output: TypeError: Object [object Object] has no method 'setAttributes'

inputField.setAttributes("value", longstring);
Heckman answered 30/8, 2014 at 14:52 Comment(5)
Indeed the alternative to sendKeys would be to set the value of the input DOM element directly. However, you show only fragment of how you try to do it and you don't explain how the program "crashes" exactly. ("Crashes" is not precise at all.)Acrobatics
Sorry, I updated the Error message in the edit.Heckman
Your code is still showing only fragments of how you do it. You don't show how input gets a value. You do show how inputField gets a value but not input, which is a different variable.Acrobatics
That was unfortunately a typo. It should be inputField throughout. With .value = longstring the program executes fine, but doesn't actually set the value.Heckman
Similar for Python: Set attribute of an element using webdriver at SQASurpass
B
60

Try to set the element's value using the executeScript method of JavascriptExecutor:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
Barbabra answered 30/8, 2014 at 15:35 Comment(13)
I get the same error as when I try to do .value = longstring Error: ElementNotVisibleError: element not visibleHeckman
Could you please add sample of your html? Because for google this code work excellent. Possibly problem with your element on page (it's hidden i think)Barbabra
I'm actually using this example to test it with google. Could you put your code that worked for you here, please?Heckman
here you are. driver.executeScript("document.getElementById('gbqfq').setAttribute('value','Selenium Web Driver')");Barbabra
Indeed it works, I tried getElementById and used q which was the name of the inputfield instead of the real id. Thanks.Heckman
In Python Selenium it's execute_scriptAristophanes
this is so beautiful, works on stubborn modern JS forms, and makes me love you like tapirs love twigs python driver.execute_script("document.getElementById('an_id').setAttribute('value', 'my_username_or_w/e')")Amnesia
Seems to work but doesn't for file input fields. Even though calling getAttribute("value") on the element returns the string I used in setAttribute("xxx"), the file input field still thinks that no file has been selected. Either that or the change event hasn't been fired...Bagby
Can I see the solution in Ruby please?Girgenti
It is worth to remaind that JS code could be checked in browser console before executing from webdriver.Squamous
For me when used new lines (\n) this worked webdriver.executeScript(document.getElementsByClassName('CLASS').innerHTML=`${text}`;Amateur
OP explicitly said for NodeJSScission
This doesn't work for me either, using selenium webdriver and java/kotlin. No errors - it just doesn't do anything.Clergyman
H
15

Extending from the correct answer of Andrey-Egorov using .executeScript() to conclude my own question example:

inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);
Heckman answered 31/8, 2014 at 2:55 Comment(3)
Yeah, this also will work. But also can be modified, to be more simplier: driver.executeScript("arguments[0].setAttribute('value', arguments[1])", inputField, longstring);Barbabra
driver.executeScript("arguments[0].value = '" + longstring + "'", inputField) is another possible improvement that also works with textAreas (I've only tested in Chrome, though)Educative
A slight modification to the above 2 ideas because at least in my context I was trying to set a textarea and it complained about the syntax. This is in protractor: browser.executeScript("arguments[0].value=arguments[1].toString()", inputField, longstring); I also found that to make the field update, it helped to then inputField.sendKeys(" "), where in my context the extra space was harmless.Kendrick
N
13

Thanks to Andrey Egorov, in my case with python setAttribute not working, but I found I can set the property directly,

Try this code:

driver.execute_script("document.getElementById('q').value='value here'")
Nuncia answered 14/4, 2017 at 3:48 Comment(0)
C
4

An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:

inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
    inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
    inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
    for(int i = 0; i < 10; i++) {
        inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
    }
}

Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS is enabled (which can cause other issues), but it works fine for Firefox and Chrome.

Carraway answered 4/2, 2016 at 17:19 Comment(0)
M
3

In a nutshell, this is the code which works for me :)

WebDriver driver;
WebElement element;
String value;

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
Mvd answered 16/9, 2019 at 14:1 Comment(0)
L
2

Thanks to Andrey-Egorov and this answer, I've managed to do it in C#

IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
Lippmann answered 19/10, 2017 at 20:39 Comment(2)
What's new in your answer in comparison with previous answers?Mulligatawny
@Stepan - not much, but none of the answers were in C# which is what I was looking for but couldn't find it anywhere. So here it is. It could help someone like me in the future.Lippmann
G
1

If you want to use some variable, you may use this way:

String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
Gonzalez answered 13/3, 2020 at 20:10 Comment(1)
When writing a code snippet, use the code icon to write them.Plasty
C
0
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");
Cataldo answered 26/4, 2019 at 16:24 Comment(1)
Hello! While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Muscular
J
0

Thanks guys, here's how I've managed to do this in Java

public static void sendKeysJavascript(By element, String keysToSend) {
    WebElement el = driver.findElement(element);
    JavascriptExecutor ex = (JavascriptExecutor) driver;
    ex.executeScript("arguments[0].value='"+ keysToSend +"';", el);
}
Jacelynjacenta answered 30/4, 2021 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.