Skip to main content
SeleniumDecoded

JavaScript Executor

Execute JavaScript directly in the browser for advanced interactions and DOM manipulation.

Selenium 3 & 4 Medium

The JavaScript Executor lets you run JavaScript code directly in the browser, bypassing Selenium’s normal interaction methods. This is useful for complex scenarios that Selenium can’t handle natively.

Basic JavaScript Execution

Execute JavaScript
Selenium 3 & 4 Stable
import org.openqa.selenium.JavascriptExecutor;
JavascriptExecutor js = (JavascriptExecutor) driver;
// Execute script with no return value
js.executeScript("console.log('Hello from Selenium')");
// Execute script that returns a value
String title = (String) js.executeScript("return document.title");
System.out.println("Page title: " + title);
// Get return value as different types
Long scrollHeight = (Long) js.executeScript("return document.body.scrollHeight");
Boolean isReady = (Boolean) js.executeScript("return document.readyState === 'complete'");
# Execute script with no return value
driver.execute_script("console.log('Hello from Selenium')")
# Execute script that returns a value
title = driver.execute_script("return document.title")
print(f"Page title: {title}")
# Get return value as different types
scroll_height = driver.execute_script("return document.body.scrollHeight")
is_ready = driver.execute_script("return document.readyState === 'complete'")
// Execute script with no return value
await driver.executeScript("console.log('Hello from Selenium')");
// Execute script that returns a value
const title = await driver.executeScript('return document.title');
console.log(`Page title: ${title}`);
// Get return value as different types
const scrollHeight = await driver.executeScript('return document.body.scrollHeight');
const isReady = await driver.executeScript("return document.readyState === 'complete'");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Execute script with no return value
js.ExecuteScript("console.log('Hello from Selenium')");
// Execute script that returns a value
string title = (string)js.ExecuteScript("return document.title");
Console.WriteLine($"Page title: {title}");
// Get return value as different types
long scrollHeight = (long)js.ExecuteScript("return document.body.scrollHeight");
bool isReady = (bool)js.ExecuteScript("return document.readyState === 'complete'");

Passing Arguments to JavaScript

JavaScript with Arguments
Selenium 3 & 4 Stable
JavascriptExecutor js = (JavascriptExecutor) driver;
// Pass WebElement as argument
WebElement button = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click()", button);
// Pass multiple arguments
WebElement input = driver.findElement(By.id("name"));
String value = "John Doe";
js.executeScript("arguments[0].value = arguments[1]", input, value);
// Pass various types
js.executeScript(
"console.log(arguments[0], arguments[1], arguments[2])",
"string", 42, true
);
// Return element information
String tagName = (String) js.executeScript(
"return arguments[0].tagName", button
);
# Pass WebElement as argument
button = driver.find_element(By.ID, "submit")
driver.execute_script("arguments[0].click()", button)
# Pass multiple arguments
input_field = driver.find_element(By.ID, "name")
value = "John Doe"
driver.execute_script("arguments[0].value = arguments[1]", input_field, value)
# Pass various types
driver.execute_script(
"console.log(arguments[0], arguments[1], arguments[2])",
"string", 42, True
)
# Return element information
tag_name = driver.execute_script("return arguments[0].tagName", button)
// Pass WebElement as argument
const button = await driver.findElement(By.id('submit'));
await driver.executeScript('arguments[0].click()', button);
// Pass multiple arguments
const input = await driver.findElement(By.id('name'));
const value = 'John Doe';
await driver.executeScript('arguments[0].value = arguments[1]', input, value);
// Pass various types
await driver.executeScript(
'console.log(arguments[0], arguments[1], arguments[2])',
'string', 42, true
);
// Return element information
const tagName = await driver.executeScript('return arguments[0].tagName', button);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Pass WebElement as argument
IWebElement button = driver.FindElement(By.Id("submit"));
js.ExecuteScript("arguments[0].click()", button);
// Pass multiple arguments
IWebElement input = driver.FindElement(By.Id("name"));
string value = "John Doe";
js.ExecuteScript("arguments[0].value = arguments[1]", input, value);
// Pass various types
js.ExecuteScript(
"console.log(arguments[0], arguments[1], arguments[2])",
"string", 42, true
);
// Return element information
string tagName = (string)js.ExecuteScript("return arguments[0].tagName", button);

Scrolling

Scroll Operations
Selenium 3 & 4 Stable
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll to bottom of page
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// Scroll to top
js.executeScript("window.scrollTo(0, 0)");
// Scroll by specific amount
js.executeScript("window.scrollBy(0, 500)"); // Down 500px
js.executeScript("window.scrollBy(0, -200)"); // Up 200px
// Scroll element into view
WebElement element = driver.findElement(By.id("footer"));
js.executeScript("arguments[0].scrollIntoView(true)", element);
// Scroll into view with options
js.executeScript(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})",
element
);
// Scroll within a container (overflow scroll)
WebElement container = driver.findElement(By.id("scroll-container"));
js.executeScript("arguments[0].scrollTop = arguments[0].scrollHeight", container);
# Scroll to bottom of page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
# Scroll to top
driver.execute_script("window.scrollTo(0, 0)")
# Scroll by specific amount
driver.execute_script("window.scrollBy(0, 500)") # Down 500px
driver.execute_script("window.scrollBy(0, -200)") # Up 200px
# Scroll element into view
element = driver.find_element(By.ID, "footer")
driver.execute_script("arguments[0].scrollIntoView(true)", element)
# Scroll into view with options
driver.execute_script(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})",
element
)
# Scroll within a container (overflow scroll)
container = driver.find_element(By.ID, "scroll-container")
driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", container)
// Scroll to bottom of page
await driver.executeScript('window.scrollTo(0, document.body.scrollHeight)');
// Scroll to top
await driver.executeScript('window.scrollTo(0, 0)');
// Scroll by specific amount
await driver.executeScript('window.scrollBy(0, 500)'); // Down 500px
await driver.executeScript('window.scrollBy(0, -200)'); // Up 200px
// Scroll element into view
const element = await driver.findElement(By.id('footer'));
await driver.executeScript('arguments[0].scrollIntoView(true)', element);
// Scroll into view with options
await driver.executeScript(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})",
element
);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Scroll to bottom of page
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
// Scroll to top
js.ExecuteScript("window.scrollTo(0, 0)");
// Scroll by specific amount
js.ExecuteScript("window.scrollBy(0, 500)"); // Down 500px
js.ExecuteScript("window.scrollBy(0, -200)"); // Up 200px
// Scroll element into view
IWebElement element = driver.FindElement(By.Id("footer"));
js.ExecuteScript("arguments[0].scrollIntoView(true)", element);
// Scroll into view with options
js.ExecuteScript(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})",
element
);

Clicking Elements

When normal clicks don’t work:

JavaScript Click
Selenium 3 & 4 Medium
JavascriptExecutor js = (JavascriptExecutor) driver;
// Element obscured by overlay
WebElement hiddenButton = driver.findElement(By.id("hidden-btn"));
js.executeScript("arguments[0].click()", hiddenButton);
// Click at specific coordinates
js.executeScript(
"document.elementFromPoint(100, 200).click()"
);
// Trigger click event
js.executeScript(
"arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))",
hiddenButton
);
# Element obscured by overlay
hidden_button = driver.find_element(By.ID, "hidden-btn")
driver.execute_script("arguments[0].click()", hidden_button)
# Click at specific coordinates
driver.execute_script("document.elementFromPoint(100, 200).click()")
# Trigger click event
driver.execute_script(
"arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))",
hidden_button
)
// Element obscured by overlay
const hiddenButton = await driver.findElement(By.id('hidden-btn'));
await driver.executeScript('arguments[0].click()', hiddenButton);
// Click at specific coordinates
await driver.executeScript('document.elementFromPoint(100, 200).click()');
// Trigger click event
await driver.executeScript(
"arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))",
hiddenButton
);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Element obscured by overlay
IWebElement hiddenButton = driver.FindElement(By.Id("hidden-btn"));
js.ExecuteScript("arguments[0].click()", hiddenButton);
// Click at specific coordinates
js.ExecuteScript("document.elementFromPoint(100, 200).click()");
// Trigger click event
js.ExecuteScript(
"arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))",
hiddenButton
);

Modifying Page Content

DOM Manipulation
Selenium 3 & 4 Medium
JavascriptExecutor js = (JavascriptExecutor) driver;
// Change element text
js.executeScript(
"document.getElementById('message').innerText = 'New text'"
);
// Set input value (bypasses events)
WebElement input = driver.findElement(By.id("email"));
js.executeScript("arguments[0].value = 'test@example.com'", input);
// Trigger input event after setting value
js.executeScript(
"arguments[0].dispatchEvent(new Event('input', {bubbles: true}))",
input
);
// Remove element
js.executeScript("arguments[0].remove()",
driver.findElement(By.id("annoying-popup"))
);
// Add/remove class
js.executeScript("arguments[0].classList.add('highlight')", input);
js.executeScript("arguments[0].classList.remove('disabled')", input);
// Change style
js.executeScript("arguments[0].style.border = '2px solid red'", input);
// Set attribute
js.executeScript("arguments[0].setAttribute('data-test', 'value')", input);
# Change element text
driver.execute_script(
"document.getElementById('message').innerText = 'New text'"
)
# Set input value (bypasses events)
input_field = driver.find_element(By.ID, "email")
driver.execute_script("arguments[0].value = 'test@example.com'", input_field)
# Trigger input event after setting value
driver.execute_script(
"arguments[0].dispatchEvent(new Event('input', {bubbles: true}))",
input_field
)
# Remove element
driver.execute_script("arguments[0].remove()",
driver.find_element(By.ID, "annoying-popup")
)
# Add/remove class
driver.execute_script("arguments[0].classList.add('highlight')", input_field)
driver.execute_script("arguments[0].classList.remove('disabled')", input_field)
# Change style
driver.execute_script("arguments[0].style.border = '2px solid red'", input_field)
# Set attribute
driver.execute_script("arguments[0].setAttribute('data-test', 'value')", input_field)
// Change element text
await driver.executeScript(
"document.getElementById('message').innerText = 'New text'"
);
// Set input value (bypasses events)
const input = await driver.findElement(By.id('email'));
await driver.executeScript("arguments[0].value = 'test@example.com'", input);
// Trigger input event after setting value
await driver.executeScript(
"arguments[0].dispatchEvent(new Event('input', {bubbles: true}))",
input
);
// Remove element
const popup = await driver.findElement(By.id('annoying-popup'));
await driver.executeScript('arguments[0].remove()', popup);
// Add/remove class
await driver.executeScript("arguments[0].classList.add('highlight')", input);
// Change style
await driver.executeScript("arguments[0].style.border = '2px solid red'", input);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Change element text
js.ExecuteScript(
"document.getElementById('message').innerText = 'New text'"
);
// Set input value (bypasses events)
IWebElement input = driver.FindElement(By.Id("email"));
js.ExecuteScript("arguments[0].value = 'test@example.com'", input);
// Trigger input event after setting value
js.ExecuteScript(
"arguments[0].dispatchEvent(new Event('input', {bubbles: true}))",
input
);
// Remove element
js.ExecuteScript("arguments[0].remove()",
driver.FindElement(By.Id("annoying-popup"))
);
// Add/remove class
js.ExecuteScript("arguments[0].classList.add('highlight')", input);
// Change style
js.ExecuteScript("arguments[0].style.border = '2px solid red'", input);

Waiting for Page State

Page Load Conditions
Selenium 3 & 4 Stable
JavascriptExecutor js = (JavascriptExecutor) driver;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
// Wait for document ready
wait.until(driver -> js.executeScript("return document.readyState").equals("complete"));
// Wait for jQuery to finish
wait.until(driver -> (Boolean) js.executeScript("return jQuery.active === 0"));
// Wait for Angular
wait.until(driver -> (Boolean) js.executeScript(
"return window.getAllAngularTestabilities().every(t => t.isStable())"
));
// Wait for React (general approach)
wait.until(driver -> (Boolean) js.executeScript(
"return !document.querySelector('[data-loading]')"
));
// Custom condition - wait for specific element to exist in DOM
wait.until(driver -> js.executeScript(
"return document.querySelector('#dynamic-content') !== null"
));
wait = WebDriverWait(driver, 30)
# Wait for document ready
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
# Wait for jQuery to finish
wait.until(lambda d: d.execute_script("return jQuery.active === 0"))
# Wait for Angular
wait.until(lambda d: d.execute_script(
"return window.getAllAngularTestabilities().every(t => t.isStable())"
))
# Wait for React (general approach)
wait.until(lambda d: d.execute_script(
"return !document.querySelector('[data-loading]')"
))
# Custom condition - wait for specific element
wait.until(lambda d: d.execute_script(
"return document.querySelector('#dynamic-content') !== null"
))
// Wait for document ready
await driver.wait(async () => {
return await driver.executeScript('return document.readyState') === 'complete';
}, 30000);
// Wait for jQuery to finish
await driver.wait(async () => {
return await driver.executeScript('return jQuery.active === 0');
}, 30000);
// Custom condition
await driver.wait(async () => {
return await driver.executeScript(
"return document.querySelector('#dynamic-content') !== null"
);
}, 30000);
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
// Wait for document ready
wait.Until(d => js.ExecuteScript("return document.readyState").Equals("complete"));
// Wait for jQuery to finish
wait.Until(d => (bool)js.ExecuteScript("return jQuery.active === 0"));
// Custom condition
wait.Until(d => (bool)js.ExecuteScript(
"return document.querySelector('#dynamic-content') !== null"
));

Common Use Cases

ScenarioJS Solution
Element behind overlayelement.click() via JS
Scroll to elementscrollIntoView()
Set hidden inputelement.value = x
Get computed stylegetComputedStyle()
Trigger eventsdispatchEvent()
Wait for frameworkCheck framework state

Best Practices

  1. Use Selenium methods first - JS is a last resort
  2. Always trigger events when setting values programmatically
  3. Handle errors - JS exceptions don’t always surface cleanly
  4. Keep scripts simple - Complex JS is hard to debug
  5. Consider maintainability - JS bypasses normal user flow

Next Steps