How to handle scroll function using
JavaScriptExecutor?
What is JavaScriptExecutor in Selenium?
JavaScriptExecutor is an interface in Selenium that lets you execute JavaScript code directly in the context of the browser.
It’s useful when:
- Selenium’s regular API cannot interact with certain elements (hidden, complex, or dynamically loaded).
- You need to perform actions like scrolling, clicking via JS, or retrieving JS-only data.
All WebDriver implementations (Chrome, Firefox, etc.) support it.
How to use:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello from JS!');");
How to Handle Scroll Events in Selenium with JavaScriptExecutor?
1. Scroll to Bottom of the Page
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
2. Scroll to a Specific WebElement
WebElement element = driver.findElement(By.id("targetElement"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);
- This scrolls the page until the specified element is visible in the viewport.
3. Scroll by Pixel Value (Vertical or Horizontal)
// Scroll down 500 pixels vertically
js.executeScript("window.scrollBy(0, 500);");
// Scroll right 300 pixels horizontally
js.executeScript("window.scrollBy(300, 0);");
Summary Table
Scroll Action | Code Example |
Scroll to bottom | js.executeScript(“window.scrollTo(0, document.body.scrollHeight);”); |
Scroll to element | js.executeScript(“arguments[0].scrollIntoView(true);”, element); |
Scroll by pixels (down/up) | js.executeScript(“window.scrollBy(0, 500);”); |
Scroll by pixels (right/left) | js.executeScript(“window.scrollBy(300, 0);”); |
Tip:
Always cast your driver to JavascriptExecutor as shown:
JavascriptExecutor js = (JavascriptExecutor) driver;