Answer
JavascriptExecutor in Selenium
JavascriptExecutor is an interface that lets you run JavaScript code in the browser context from your Selenium test.
Basic Usage
Java
// Cast WebDriver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Execute JS — no return value
js.executeScript("window.scrollTo(0, 500);");
// Execute JS — with return value
String title = (String) js.executeScript("return document.title;");
Long count = (Long) js.executeScript("return document.querySelectorAll('.item').length;");
// Pass element as argument to JS
WebElement btn = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click();", btn);
// arguments[0] = first passed argument (btn)
Common Use Cases
1. Click When Normal Click Fails
Java
// Some elements reject regular .click() due to:
// - covered by overlay
// - hidden but exists in DOM
// - Angular intercepting click
WebElement btn = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click();", btn);
2. Scroll to Element / Position
Java
// Scroll to specific element
WebElement element = driver.findElement(By.id("footer-section"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
// Scroll to bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
// Scroll by pixels
js.executeScript("window.scrollBy(0, 300);"); // scroll down 300px
// Scroll element into center of viewport
js.executeScript("arguments[0].scrollIntoView({behavior:'smooth', block:'center'});", element);
3. Set Input Value Directly (Bypassing Events)
Java
// For date pickers, read-only fields, custom components
WebElement dateInput = driver.findElement(By.id("datepicker"));
js.executeScript("arguments[0].value = '2025-12-31';", dateInput);
// If you also need to trigger change event
js.executeScript(
"arguments[0].value = arguments[1];" +
"arguments[0].dispatchEvent(new Event('change'));",
dateInput, "2025-12-31");
4. Get/Set Element Properties
Java
// Get computed style
String color = (String) js.executeScript(
"return window.getComputedStyle(arguments[0]).backgroundColor;", element);
// Check if element is in viewport
Boolean isVisible = (Boolean) js.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return (rect.top >= 0 && rect.bottom <= window.innerHeight);", element);
// Get innerHTML
String html = (String) js.executeScript("return arguments[0].innerHTML;", element);
// Remove readonly attribute
js.executeScript("arguments[0].removeAttribute('readonly');", element);
// Remove disabled attribute
js.executeScript("arguments[0].removeAttribute('disabled');", element);
5. Handle Alerts and Popups
Java
// Create an alert via JS (for testing alert handlers)
js.executeScript("alert('Test alert');");
// Or get localStorage values
String token = (String) js.executeScript("return localStorage.getItem('auth_token');");
js.executeScript("localStorage.setItem('auth_token', arguments[0]);", "test_token_abc");
js.executeScript("localStorage.clear();");
6. Highlight Elements (Debugging)
Java
// Turn element border red temporarily — useful during debugging
public void highlight(WebElement el) {
String originalStyle = el.getAttribute("style");
js.executeScript(
"arguments[0].style.border = '3px solid red';", el);
Thread.sleep(500);
js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);", el, originalStyle);
}
7. executeAsyncScript — Async Operations
Java
// Wait for async JS to complete (e.g., AJAX response)
String result = (String) js.executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"fetch('/api/data').then(r => r.json()).then(d => callback(d.status));");
System.out.println("API status: " + result);
When to Use JS vs Regular Selenium
| Use Regular Selenium | Use JavascriptExecutor |
|---|---|
| Standard visible elements | Hidden/overlaid elements |
| Normal clicks | Element intercepted by overlay |
| sendKeys on regular inputs | Read-only / custom date pickers |
| Standard scroll | Scroll to precise position |
| getAttribute() | computed styles, localStorage |
