How to scroll the webpage to the top of the page.
I know scrolling the page to the bottom is:
window.scrollTo(0,document.body.scrollHeight)
just like that is it possible to scroll the page to the top
Javascript method ScrollBy() scrolls the web page to the specific number of pixels. The syntax of ScrollBy() methods is : executeScript("window. scrollBy(x-pixels,y-pixels)");
Hence, to scroll up or down with Selenium, a JavaScriptExecutor is a must. The scrollBy() method involves two parameters, x, and y, that represent the horizontal and vertical pixel values, respectively.
To scroll up to the top of a webpage using Selenium, you can use the execute_script() function to execute the JavaScript function window. scrollTo() and pass '0' for the second parameter.
Selenium runs the commands in Javascript with the execute_script() method. For scrolling down to the bottom of the page, we have to pass (0, document. body. scrollHeight) as parameters to the method scrollBy().
To scroll to the top of the page, just scroll to the 0, 0
:
window.scrollTo(0, 0);
Or, as an alternative option, you can scroll into view of the header
element (or some other element on top):
WebElement element = driver.findElement(By.tagName("header"));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].scrollIntoView();", element);
Use action class, as some UI frameworks don't work well with JavaScript scrollTO
actions.sendKeys(keys.Home).build().perform();
actions.sendKeys(keys.END).build().perform();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With