</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to execute JavaScript in Selenium?

Use JavascriptExecutor interface by casting the WebDriver instance and calling executeScript() to run JavaScript in the browser.

Answer

JavaScript can be executed in Selenium using the JavascriptExecutor interface.

Cast the driver:

Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("{Java script code}");

Common use cases with examples:

Scroll to bottom:

Java
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

Click a hidden or overlapping element:

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

Set value on readonly input:

Java
WebElement field = driver.findElement(By.id("datePicker"));
js.executeScript("arguments[0].value=''2025-12-31'';", field);

Scroll element into view:

Java
js.executeScript("arguments[0].scrollIntoView(true);", element);

Return a value:

Java
String title = (String) js.executeScript("return document.title;");
Long count = (Long) js.executeScript("return document.querySelectorAll(''.item'').length;");

Highlight element (debugging):

Java
js.executeScript("arguments[0].style.background=''yellow'';", element);

When to use JavascriptExecutor:

  • Element not interactable with standard Selenium commands
  • Need to bypass browser focus/scroll restrictions
  • Setting values on read-only or disabled inputs
  • Checking page state via DOM properties

Follow AutomateQA

Related Topics