Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to focus an element in Selenium WebDriver using Java

What's the equivalent of selenium.focus() for WebDriver?

element.sendKeys(""); 

or

new Actions(driver).moveToElement(element).perform(); 

I have tried both of them and they worked, but which one would always work on all elements?

Which one is the correct way for any elements (such as button, link etc.)? This matters to me because the function will be used on different UI's.

like image 861
questions Avatar asked Jul 05 '12 02:07

questions


People also ask

How do you change focus in Selenium?

Selenium driver object can access the elements of the parent window. In order to switch its focus from the parent to the new popup tab, we shall take the help of the switchTo(). window method and pass the window handle id of the popup as an argument to the method.

Which is the correct JavascriptExecutor method?

JavascriptExecutor consists of two methods that handle all essential interactions using JavaScript in Selenium. executeScript method – This method executes the test script in the context of the currently selected window or frame. The script in the method runs as an anonymous function.

How will you switch focus back from a frame in Selenium?

Selenium by default has access to the main browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. To again focus back to the current page from frame, the method switchTo(). defaultContent() is used.


1 Answers

The following code -

element.sendKeys("");

tries to find an input tag box to enter some information, while

new Actions(driver).moveToElement(element).perform();

is more appropriate as it will work for image elements, link elements, dropdown boxes etc.

Therefore using moveToElement() method makes more sense to focus on any generic WebElement on the web page.

For an input box you will have to click() on the element to focus.

new Actions(driver).moveToElement(element).click().perform();

while for links and images the mouse will be over that particular element,you can decide to click() on it depending on what you want to do.

If the click() on an input tag does not work -

Since you want this function to be generic, you first check if the webElement is an input tag or not by -

if("input".equals(element.getTagName()){    element.sendKeys(""); }  else{    new Actions(driver).moveToElement(element).perform();  } 

You can make similar changes based on your preferences.

like image 96
Hari Reddy Avatar answered Sep 25 '22 05:09

Hari Reddy