Selenium + Java · Lesson 24 of 44

0/44 done

Module 24: JavaScript Executor

24. JavaScriptExecutor for Scrolling, Hidden Elements & DOM Hacks

16 minlesson

Your task

Implement scrollIntoViewAndClick:

  1. Accept WebDriver driver and WebElement element.
  2. Cast driver to JavascriptExecutor.
  3. Call js.executeScript("arguments[0].scrollIntoView(true);", element).
  4. Call js.executeScript("arguments[0].click();", element).

Write it in the editor, then press Check answer (Ctrl + Enter).

Executing JavaScript in Selenium

java
import org.openqa.selenium.JavascriptExecutor;

JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll element into view:
WebElement footer = driver.findElement(By.id("footer"));
js.executeScript("arguments[0].scrollIntoView(true);", footer);

// JS Click (bypasses click interception):
WebElement submitBtn = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click();", submitBtn);

// Retrieve page document readyState:
String state = (String) js.executeScript("return document.readyState;");

Key Takeaways & Walkthrough Summary

When WebDriver fails to click due to overlay interception or needs to scroll deep down a long page, JavascriptExecutor provides a direct bridge into the browser's JavaScript engine. In this lesson, you will learn when to use and when to avoid executeScript. Let's master JavascriptExecutor!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Should I replace all element.click() calls with JS click?

No! JS clicks bypass user-facing checks (e.g. checking if element is hidden or disabled), potentially giving false positive test passes. Use it only when necessary.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip