Scrolling webpage using JavaScript

In this post, we will discuss, scrolling webpage using JavaScript. We will look at Facebook front page and try to scroll to the bottom with sample code snippet. I will locate the “Developer” link at the bottom of the Facebook page and scroll the webpage and take a screenshot.

 

Vertical Scrolling a webpage

public class ScrollPageExample {
    WebDriver driver;
    

    @BeforeClass
    public void openBrowser() {
        System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");
        driver=new EdgeDriver();
        driver.get("https://www.facebook.com");
        driver.manage().window().maximize();
    }
    
    
    @Test()
    public void scrollWebPageToElement() {
        WebElement element = driver.findElement(By.linkText("Developers"));
        ((JavascriptExecutor) driver).executeScript(
                "arguments[0].scrollIntoView();", element);
        WebDriverWait wait = new WebDriverWait(driver, 120);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Developers")));
        captureScreen("ScreenAfterScroll.png");
    }
    
    public void captureScreen(String fileName) {
        File scrFile = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile, new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @AfterClass()
    public void closeBrowser() {
        driver.quit();
    }
}

 

The method scrollIntoView() very useful method while applying scrolling property to HTML page, div or frame.t scrolls the page, div or frame until the searching element is in the view.

JavaScript scrollIntoView() method

Syntax :
element.scrollIntoView();

 

Scrolling_WebPage_using_JavaScript

 

Unlike the above example, If you know the exact distance to scroll, we can use the below code :

 

//  vertical scroll - down by 500 pixels
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
//  vertical scroll - UP by 100 pixels
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-100)");

 

Horizontal Scrolling a webpage

Horizontal scroll examples:

// horizontal scroll - right by 30 pixels
js.executeScript("window.scrollBy(30,0)", "");

// horizontal scroll - left by 100
js.executeScript("window.scrollBy(-100,0)", "");