We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Get the element that currently has keyboard focus using switchTo().activeElement().
On any web page, there is at most one element with keyboard focus at a time:
This focused element is called the active element.
driver.switchTo().activeElement();WebElement that currently has keyboard focus.switchTo(), you are not switching windows or frames. You're simply asking: "Which element would receive sendKeys(...) if the user started typing now?"activeElement() gives you a direct handle to the element that currently has focus.Imagine a simple form where focus changes as you click or tab:
Currently focused ID: none
Click an element to focus it, or use Tab to move focus between fields!
id="lesson8-name", type="text"id="lesson8-email", type="email"id="lesson8-submit"driver.switchTo().activeElement() to:lesson8-email.123456789101112WebElement active = driver.switchTo().activeElement();
String tagName = active.getTagName();
String activeId = active.getAttribute("id");
active.sendKeys("test@example.com");
active.sendKeys("\t");
WebElement newActive = driver.switchTo().activeElement();
String newActiveId = newActive.getAttribute("id");
driver.quit();WebElement. No locator (By.id, etc.) is needed.getTagName() tells you what kind of element it is.Right after a page or modal opens, call activeElement() to confirm the correct field is focused by default.
Combine activeElement() with sendKeys(Keys.TAB) to test apps that support full keyboard navigation.
Check its tag and ID – if you get <body> or an unexpected ID, your app's focus behavior might not match requirements.