I want to bring focus to a given object present in a web page using selenium web driver. Tried with Action class but it doesn't work. Is there a way to accomplish this? I am using selenium web driver with java.
Asked
Active
Viewed 3,558 times
3

undetected Selenium
- 183,867
- 41
- 278
- 352

Durga_Prasad_Patro
- 51
- 1
- 10
-
1Does this answer your question? [Correct way to focus an element in Selenium WebDriver using Java](https://stackoverflow.com/questions/11337353/correct-way-to-focus-an-element-in-selenium-webdriver-using-java) – Jonah Dec 29 '19 at 13:03
1 Answers
4
HTMLElement.focus()
The HTMLElement.focus() method sets focus on the desired element, if it can be focused. The focused element is the element which can receive the keyboard and similar events by default.
This usecase
Generally, invoking click()
will set the focus on the desired element.
driver.findElement(By.cssSelector("element_cssSelector")).click();
Ideally, you should induce WebDriverWait for the elementToBeClickable()
while invoking the click()
to set the focus as follows:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("element_cssSelector"))).click();
At times, you may need to use moveToElement()
method from Actions Class inconjunction with click()
to set the focus as follows:
new Actions(driver).moveToElement(element).click().build().perform();
You can also use the executeScript()
method from JavascriptExecutor Interface to set the focus as follows:
((JavascriptExecutor)driver).executeScript("document.getElementById('element_ID').focus();");
But in this case, you need to ensure that the specific window is focused and to achive that you can use the following line of code:
((JavascriptExecutor)driver).executeScript("window.focus();");

undetected Selenium
- 183,867
- 41
- 278
- 352