Test if an element is focused using Selenium Webdriver
I'm really surprised I can't find references on the internet to testing for element focus using Selenium Webdriver.
I'm wanting to check when when a form submission is attempted with a mandatory field missed, focus is moved to the empty field. But I cannot see any way to do this using the WebDriver API.
Thanks for any help.
driver.switchTo().activeElement() will return the currently focused WebElement. Equality is well defined for WebElement, so you can call element.equals(driver.switchTo().activeElement()).
Calling the slightly misleading named driver.switchTo().activeElement() does not in fact switch focus, neither does driver.findElement(), so you do not need to switchTo().defaultContent() after; in fact, doing so would probably blur the current element.
returns the currently focused element.
Makes sure you switch back after using
Also if nothing is focused the body of the document is returned.
Take a look at this question as well.
You can find the active element using selector 'dom=document.activeElement'. Then you can assert whether it's the element you want it to be focused or not.
The WebDriver is supposed to change focus when you use Driver.FindElement calls. So you're last element in the Driver context is active.
NOTE: This breaks for any elements injected dynamic (e.g. jQuery), so you'd need to go the script route then.
@danielwagner-hall The boolean bb = driver.switchTo().activeElement().equals(driver.findElement(By.id("widget_113_signup_username"))); will always pass but it doesn't prove that the element is brought into focus if the element is out of view.
NB: Unable to comment as not enough reputation points.
One way of approaching this could be to use webElement.getLocation().getX(); getY() methods and reference the coordinates on the page and verify its focus.