QA
Junior QASeleniumFree question

When and how do you use JavascriptExecutor?

60-second answer

JavascriptExecutor lets Selenium run JavaScript directly in the browser. I use it when normal WebDriver commands can't do the job: scrolling to an element or to the bottom of a page, clicking an element hidden behind an overlay as a last resort, reading values not exposed in the DOM, setting a value on a read-only date field, or highlighting elements for debugging. I cast the driver to JavascriptExecutor and call executeScript. But I use it sparingly, because a JS click bypasses real user behaviour and can hide real bugs.

Explanation

  • executeScript(script, args...) → arguments available as arguments[0] etc.
  • executeAsyncScript for async code.
  • Return values come back as Java objects (Long, String, Boolean, WebElement, List).

Use cases: scrollIntoView, window.scrollTo, document.readyState, element.click(), removing a sticky banner in test environments.

Warning: if a real user can't click the button because an overlay covers it, a JS click makes the test pass while the bug stays.

Example

An infinite-scroll product list: scroll to the bottom repeatedly until no new items load, then count products.

Sample code

JavascriptExecutor js = (JavascriptExecutor) driver;

WebElement footer = driver.findElement(By.id("footer"));
js.executeScript("arguments[0].scrollIntoView({block:'center'});", footer);
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

String state = (String) js.executeScript("return document.readyState;");
js.executeScript("arguments[0].value='2026-12-25';", driver.findElement(By.id("date")));