I like to use a combination of techniques, the first involving a 'dependableClick()' which I have modified slightly starting with some code I found here on SE:
public void dependableClick(By by) throws InterruptedException
{
final int MAXIMUM_WAIT_TIME = 10;
final int MAX_STALE_ELEMENT_RETRIES = 5;
WebDriverWait wait = new WebDriverWait(driver, MAXIMUM_WAIT_TIME);
int retries = 0;
while (true) {
try {
wait.until(ExpectedConditions.elementToBeClickable(by)).click();
return;
} catch (StaleElementReferenceException e) {
if (retries < MAX_STALE_ELEMENT_RETRIES) {
retries++;
continue;
}
else {
throw e;
}
} catch (WebDriverException e2) {
System.out.println("dependableClick catches WebDriverException...");
Thread.sleep(500);
if (retries < MAX_STALE_ELEMENT_RETRIES) {
retries++;
continue;
}
else {
throw e2;
}
}
}
}
This helps anytime I need to click an element that, for any number of reasons, doesn't lend itself easily to being clicked. I then leverage that in another method specifically for entering text:
public void inputTextToElement(By by, String text) throws Exception {
dependableClick(by); // get focus on element
driver.findElement(by).clear();
driver.findElement(by).sendKeys(text);
}
In this method, the dependableClick() gets the focus after which we can continue as normal. An example call might look like this:
inputTextToElement(By.cssSelector(".inputbox_firstname"), "John");
With Chrome in particular, I find these sorts of 'brute force' helper methods to be invaluable for many otherwise simple tasks. When I start running into stale elements and missed clicks and such, I start looking into helper methods like these to encapsulate the error trapping that is sometimes necessary. Once these are working, they really help to get me back into the flow of writing automation without having to trip over the same nonsense again and again.
That said, I'm sure there are infinitely more elegant ways to approach this than the code I'm showing here, but this is working for me.