I've been trying to fix this issue for a while now, none of the existing questions help. I'm using the node implementation of Selenium WebDriver, version ^4.0.0-alpha.1 and testing it on Chrome using the latest ChromeDriver.
I'm trying to clear the text of an <input/>
, whose type="email"
. WebDriver has a built in command for this, but when I execute it the input doesn't clear (and there's no error):
// This populates the text field, no problem
driver.findElement(By.id("model-auth-email")).sendKeys("[email protected]");
// This is executed without error, but nothing happens, text field isn't cleared
driver.findElement(By.id("model-auth-email")).clear();
I can't use the CTRL+a & BACKSPACE method since I'm using a Mac and it would be CMD+a. And ChromeDriver has had (still unresolved) issues supporting the native OSX CMD button input for like 6 years, according the various threads I could find.
I could also do something like loop BACKSPACE inputs until it's cleared, though that's pretty hacky.
Any ideas on why .clear()
is silently not working?
You can use the onfocus attribute in JavaScript to clear a textbox or an input box when somebody sets focus on the field. If you are using jQuery, then use the . focus() method to clear the field.
What seems to be working for us is to:
select()
method of the <input>
element.Here's a clear
function that will do just that:
async function clear(drv, web_elt) {
await drv.executeScript(elt => elt.select(), web_elt);
await web_elt.sendKeys(Key.BACK_SPACE);
}
Whereby:
drv
is an instance of WebDriver
web_elt
is an instance of WebElement
executeScript
is stringified and receives the <input>
element wrapped in web_elt
as a parameterFind below a demo and the full code for it.
This is running on Node.js 11 with selenium-webdriver
v4.
Make sure your chromedriver is in your PATH then run node index.js
// index.js
const path = require('path');
const wd = require('selenium-webdriver');
const {Key} = wd;
const driver =
(new wd.Builder)
.forBrowser(wd.Browser.CHROME)
.build();
async function clear(drv, web_elt) {
await drv.executeScript(elt => elt.select(), web_elt);
await web_elt.sendKeys(Key.BACK_SPACE);
}
async function run(drv) {
await drv.get('file://' + path.join(__dirname, 'index.html'));
await drv.sleep(1000);
await clear(drv, drv.findElement({css: 'input'}));
await drv.sleep(1000);
await clear(drv, drv.findElement({css: 'textarea'}));
await drv.sleep(1000);
await drv.quit();
}
run(driver);
<!-- index.html -->
<html>
<body>
<p>
<input type="text" value="Hello World!"/>
</p>
<p>
<textarea cols="30" rows="10">Hello World!</textarea>
</p>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With