I'm trying to verify that particular div has a scrollbar, how to do it with Selenium? Element:
<div class="checkout-mini-cart">
Code:
JavascriptExecutor jsExecutor = (JavascriptExecutor)webDriver;
String script = "var div = document.getElementsByClassName('.checkout-mini-cart');" +
"return div.scrollHeight < div.clientHeight;";
Object isScrollable = jsExecutor.executeScript(script);
It always return false because "return div.scrollHeight;" returns null. How to do it in a correct way?
We can check scroll position using Selenium. To check the position we shall use the Javascript executor. We have to verify the value of the window. pageYOffset in the browser.
Checking whether an element has a scrollbar isn't as trivial as it seems. The first formula I've written above works fine when element doesn't have a border, but when it does (especially when border is of considerable width), offset dimension can be larger than scroll dimension but the element can still be scrollable.
Many assume that width: 100vw is the same as width: 100% . This is true on a page that doesn't scroll vertically, but what you might not realize is that the viewport actually includes the scrollbars, too.
The code document.getElementsByClassName
returns an array and not a DOM element.
To check if an element is scroll-able with a script injection :
String JS_ELEMENT_IS_SCROLLABLE =
"return arguments[0].scrollHeight > arguments[0].offsetHeight;";
JavascriptExecutor jse = (JavascriptExecutor)webDriver;
WebElement container = driver.findElement(By.cssSelector(".checkout-mini-cart"));
Boolean isScrollable = (Boolean)jse.executeScript(JS_ELEMENT_IS_SCROLLABLE, container);
or by reading the properties :
WebElement container = driver.findElement(By.cssSelector(".checkout-mini-cart"));
int scrollHeight = parseInt(container.getAttribute("scrollHeight"));
int offsetHeight = parseInt(container.getAttribute("offsetHeight"));
Boolean isScrollable = scrollHeight> offsetHeight;
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