[javascript] Set value of input instead of sendKeys() - Selenium WebDriver nodejs

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);

This question is related to javascript node.js selenium selenium-webdriver

The answer is


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);

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

String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");

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);

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'")

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");

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.


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')");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java