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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With