开发者

Test if an element is focused using Selenium Webdriver

开发者 https://www.devze.com 2023-04-07 06:19 出处:网络
I\'m really surprised I can\'t findreferences on the internet to testing for element focus 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 开发者_StackOverflowis 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.


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.


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


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_si‌​gnup_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消