Selenium JavaScript Executor

JavascriptExecutor lets Selenium run raw JavaScript code directly inside the browser. It solves problems that normal Selenium commands cannot handle, like scrolling to a hidden element or clicking something regular click() refuses to touch.

Diagram: Two Ways To Reach The Browser

Your Test Script
   |
   |--- WebDriver commands ---> normal browser actions
   |
   |--- JavascriptExecutor ---> direct JavaScript injection
                                     |
                                     v
                              Browser executes raw JS

Creating A JavascriptExecutor Object

JavascriptExecutor js = (JavascriptExecutor) driver;

Scrolling The Page

js.executeScript("window.scrollBy(0, 500)");

This scrolls the page down by 500 pixels, useful when an element sits below the visible screen area.

Scrolling To A Specific Element

WebElement footer = driver.findElement(By.id("site-footer"));
js.executeScript("arguments[0].scrollIntoView(true);", footer);

This scrolls the page until the footer element becomes visible in the viewport.

Clicking An Element Using JavaScript

WebElement hiddenButton = driver.findElement(By.id("submit-btn"));
js.executeScript("arguments[0].click();", hiddenButton);

This clicks a button through JavaScript directly, bypassing overlay elements that sometimes block a normal Selenium click.

Setting A Value Without sendKeys()

WebElement emailField = driver.findElement(By.id("email"));
js.executeScript("arguments[0].value='student@estudy247.com';", emailField);

This sets text directly into an input field, occasionally useful on fields that block normal typing through custom JavaScript listeners.

Reading Page Title Through JavaScript

String title = (String) js.executeScript("return document.title;");
System.out.println(title);

This returns the page title using a JavaScript return statement instead of the standard getTitle() method.

Highlighting An Element For Debugging

WebElement field = driver.findElement(By.id("username"));
js.executeScript("arguments[0].style.border='3px solid red';", field);

This draws a red border around an element temporarily, helping a tester visually confirm the correct element was located during debugging.

Checking Page Load Status

String readyState = (String) js.executeScript("return document.readyState;");
if (readyState.equals("complete")) {
    System.out.println("Page fully loaded");
}

This checks the browser's own readiness signal, confirming every resource on the page finished loading.

When To Use JavascriptExecutor

Reach for JavascriptExecutor only when standard Selenium commands fail, such as clicking elements hidden behind sticky headers or scrolling infinite-load pages. Overusing it skips the natural interaction path a real user follows, which can hide genuine bugs a normal click would have caught.

Leave a Comment

Your email address will not be published. Required fields are marked *