How do you check scroll position using selenium?


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.

While the URL is launched, the scroll is at the top the value of window.pageYOffset is 0. As we scroll to an element, the value of the window.pageYOffset shall be greater than 0.

Syntax

JavascriptExecutor j = (JavascriptExecutor) driver;
Long v = (Long) j.executeScript("return window.pageYOffset;");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollPosition{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // get current scroll position with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      Long v = (Long) j.executeScript("return window.pageYOffset;");
      System.out.println("Scroll position after launch: " + v);
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Careers']"));
      // Javascript executor to scroll to the element
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", n);
      Thread.sleep(200);
      // get current scroll position with Javascript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      double d = (double) js.executeScript("return window.pageYOffset;");
      System.out.println("Scroll position after scrolling upto an element: "+d);
      driver.close();
   }
}

Output

Updated on: 28-Nov-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements