14

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.

SamStephens
  • 5,721
  • 6
  • 36
  • 44

5 Answers5

34

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.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
Daniel Wagner-Hall
  • 2,446
  • 1
  • 20
  • 18
  • I have a text field which id="widget_113_signup_username" . I want to verify whether the focus is on that field or not. I wrote the following code to do this. If cursor is not present on it bb = false, otherwise bb= true. Am I right? Is my code OK? boolean bb = driver.switchTo().activeElement().equals(driver.findElement(By.id("widget_113_signup_username"))); – Ripon Al Wasim Aug 30 '12 at 12:05
4
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

Community
  • 1
  • 1
Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128
0

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.

Brett Veenstra
  • 47,674
  • 18
  • 70
  • 86
0

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.

Ashkan Aryan
  • 3,504
  • 4
  • 30
  • 44
-1

@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.

Django_Tester
  • 139
  • 1
  • 3
  • 16