Reputation: 5871
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.
I will be able to find the focused element using a JavascriptExecutor. But reading the FAQ makes me think there must be some way to perform the check using the driver itself.
Thanks for any help.
Upvotes: 15
Views: 29556
Reputation: 139
@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.
Upvotes: -1
Reputation: 2606
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.
Upvotes: 35
Reputation: 48534
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.
Upvotes: 0
Reputation: 19862
driver.switchTo().activeElement();
returns the currently focused element.
Makes sure you switch back after using
driver.switchTo().defaultContent();
Also if nothing is focused the body
of the document is returned.
Take a look at this question as well.
In Selenium how do I find the "Current" object
Upvotes: 5
Reputation: 3534
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.
Upvotes: 0