When working with Selenium alone, it can be challenging to determine if an element is visible on the screen. However, by incorporating JavascriptExecutor, we can achieve this task efficiently. By utilizing JavascriptExecutor
, we can locate the desired element and pass it to the IsElementInView()
function. This function will execute Javascript commands to ascertain the position of the element in relation to the browser window's dimensions.
- If
top < 0
, the element is positioned above the visible area of the screen.
- If
bottom > height
, the element extends beyond the bottom of the screen.
- If
left < 0
, the element is off-screen to the left.
- If
right > width
, the element is located outside the visible area to the right.
If any of the specified conditions are met, then the element is considered to be off-screen. Alternatively, if none of these conditions apply, the element is deemed to be within the viewable area.
class Program
{
static IWebDriver driver;
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Manage().Window.Maximize();
String searchText = "Padding - Shorthand Property";
driver.Navigate().GoToUrl("http://www.w3schools.com/css/css_padding.asp");
IWebElement e = driver.FindElement(By.XPath("//h2[text()=" + searchText + "]"));
Console.WriteLine(IsElementInView(e));
}
public static Boolean IsElementInView(IWebElement e)
{
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
Double top = (Double)jse.ExecuteScript("return arguments[0].getBoundingClientRect().top", e);
Double bottom = (Double)jse.ExecuteScript("return arguments[0].getBoundingClientRect().bottom", e);
long left = (long)jse.ExecuteScript("return arguments[0].getBoundingClientRect().left", e);
long right = (long)jse.ExecuteScript("return arguments[0].getBoundingClientRect().right", e);
long width = (long)jse.ExecuteScript("return window.innerWidth");
long height = (long)jse.ExecuteScript("return window.innerHeight");
if (top < 0 || bottom > height || left < 0 || right > width)
{
return false;
}
return true;
}
}