September 14, 2022

How to scroll until the web element is in the center of screen using Selenium + .Net + Java Script

  September 14, 2022

 When we are using any type of reporting , if given the command to take a screenshot it takes the currently visible screen of the application. But it is possible that the validating element may be out of the visible screen.

To exactly get the element image while doing the validation, the best way is to scroll to the element location.

This can be achieved by using Java Script along with selenium WebDriver.

The below code can be used in such scenarios.

public void scrollToElementLocation(string elementXpath)
{
	var script = "arguments[0].scrollIntoView(true);";
	IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
	js.ExecuteScript(script, driver.FindElement(By.XPath(elementXpath));
}

Here we are using JavaScript because it will not fail on any element not found exceptions.

For example, if we are doing a validation by extracting a text of an element. If the element itself does not exist, the scroll to the element itself will fail and it will never reach the line where text validation occurs.

But when Java script scroll to element is used, no Element not found exception will be thrown at scroll to element method.
logoblog

Thanks for reading How to scroll until the web element is in the center of screen using Selenium + .Net + Java Script

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...