Scroll Webpage using JavaScript
Overview
In this post, we will learn how to Scroll Webpage using JavaScript. We will look at Facebook front page and try to scroll to the bottom with sample code snippet. We 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();
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)", "");
–
Selenium Tutorial on this website:
https://www.testingdocs.com/selenium-webdriver-tutorial/
More information on Selenium, visit official website: