Get Scroll Position of Web Page

To get the scroll position of web page using Selenium in Java, we have to use JavaScript to get the page offset along Y-axis, and execute this JavaScript code from Selenium JavascriptExecutor.

The following is the code snippet to get page offset / scroll position of web page along Y-axis.

</>
Copy
return window.pageYOffset;

We have to run the above JavaScript code on the webpage using Selenium’s JavascriptExecutor.

</>
Copy
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeScript("return window.pageYOffset;")

where driver is the WebDriver object.

The above statement returns a Java object, and we have to cast this object to Long datatype.

Example

In the following program, we write Selenium Java code to visit WikiPedia Main Page, and print the scroll position of the web page.

Java Program

</>
Copy
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        
    	WebDriver driver = new ChromeDriver();
        driver.get("https://en.wikipedia.org/wiki/Main_Page");
        
        JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
        Long scrollPosition = (Long) jsExecutor.executeScript("return window.pageYOffset;");
        System.out.println("Scroll Position : " + scrollPosition);	
        
        driver.quit();
    }
}

Output

Scroll Position : 0

Screenshot