Selenium, how do you check scroll position

后端 未结 3 592
我寻月下人不归
我寻月下人不归 2021-02-07 11:00

Using selenium with java, I need to test a \"Back to top\" button, so what I did is to scroll page down until \"Back to top\" button is shown (as it is shown when scrolled 25% o

相关标签:
3条回答
  • 2021-02-07 11:24

    The general principle is to check the value of window.pageYOffset in the browser. If your button scrolls completely back to the top then window.pageYOffset should have a value of 0. Assuming the driver variable holds your WebDriver instance:

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

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

    This answer initially mentioned scrollY but there's no support for it on IE. The MDN page on it, says:

    For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A 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 the "heads up".

    0 讨论(0)
  • 2021-02-07 11:24

    Louis' 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 cross-browser compatible.

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

    Here is the above code block with the modified code:

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

    Also, syntax for Ruby (what I use for my current position, assuming as before that the driver instance is accessible through the variable name, 'driver'):

    driver.execute_script('return window.pageYOffset;')
    
    0 讨论(0)
  • 2021-02-07 11:26

    if necessary, find the position scrolled to one specify div, use this code:

    JavascriptExecutor executor = (JavascriptExecutor) driver;
    Long value = (Long) executor.executeScript("return document.getElementById('container').scrollTop;");
    
    0 讨论(0)
提交回复
热议问题