Selenium, how do you check the scroll position

Using selenium with java, I need to test the "Up" button, so I did it to scroll the page until "Back to top" is displayed (as shown when scrolling 25% of the page) and click on it, this button will bring the user to the top of the page, now I need to check that this worked, and the visible part is at the top of the page. How to do it using java?

+6
source share
2 answers

The general principle is to check the value of window.pageYOffset in the browser. If your button scrolls fully back, then window.pageYOffset should be set to 0. Assuming the driver variable contains your WebDriver instance:

 JavascriptExecutor executor = (JavascriptExecutor) driver; Long value = (Long) executor.executeScript("return window.pageYOffset;"); 

You can then verify that value is 0. executeScript used to run JavaScript code in the browser.

This answer was originally mentioned by scrollY , but in IE there is no support. MDN page on it says:

For compatibility with multiple browsers, use window.pageYOffset instead of window.scrollY . In addition, older versions of Internet Explorer (<9) do not support any property, and they must be circumvented by checking other non-standard properties. Fully compatible example:

 var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; 

Thanks to R. Oosterholt for heads-up.

+15
source

Louis's answer works, but is not fully cross-browser compatible, as Internet Explorer does not support window.scrollY. I recommend using window.pageYOffset instead - this returns the same value, but is compatible with a cross browser.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY

Here is the code block above with the modified code:

 JavascriptExecutor executor = (JavascriptExecutor) driver; Long value = (Long) executor.executeScript("return window.pageYOffset;"); 

In addition, the syntax for Ruby (what I use for the current position, assuming that before that the driver instance is available through the variable name, "driver"):

 driver.execute_script('return window.pageYOffset;') 
+4
source

Source: https://habr.com/ru/post/975001/


All Articles