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 valuejs.executeScript("console.log('Hello from Selenium')");
// Execute script that returns a valueString title = (String) js.executeScript("return document.title");System.out.println("Page title: " + title);
// Get return value as different typesLong scrollHeight = (Long) js.executeScript("return document.body.scrollHeight");Boolean isReady = (Boolean) js.executeScript("return document.readyState === 'complete'");# Execute script with no return valuedriver.execute_script("console.log('Hello from Selenium')")
# Execute script that returns a valuetitle = driver.execute_script("return document.title")print(f"Page title: {title}")
# Get return value as different typesscroll_height = driver.execute_script("return document.body.scrollHeight")is_ready = driver.execute_script("return document.readyState === 'complete'")// Execute script with no return valueawait driver.executeScript("console.log('Hello from Selenium')");
// Execute script that returns a valueconst title = await driver.executeScript('return document.title');console.log(`Page title: ${title}`);
// Get return value as different typesconst 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 valuejs.ExecuteScript("console.log('Hello from Selenium')");
// Execute script that returns a valuestring title = (string)js.ExecuteScript("return document.title");Console.WriteLine($"Page title: {title}");
// Get return value as different typeslong 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 argumentWebElement button = driver.findElement(By.id("submit"));js.executeScript("arguments[0].click()", button);
// Pass multiple argumentsWebElement input = driver.findElement(By.id("name"));String value = "John Doe";js.executeScript("arguments[0].value = arguments[1]", input, value);
// Pass various typesjs.executeScript( "console.log(arguments[0], arguments[1], arguments[2])", "string", 42, true);
// Return element informationString tagName = (String) js.executeScript( "return arguments[0].tagName", button);# Pass WebElement as argumentbutton = driver.find_element(By.ID, "submit")driver.execute_script("arguments[0].click()", button)
# Pass multiple argumentsinput_field = driver.find_element(By.ID, "name")value = "John Doe"driver.execute_script("arguments[0].value = arguments[1]", input_field, value)
# Pass various typesdriver.execute_script( "console.log(arguments[0], arguments[1], arguments[2])", "string", 42, True)
# Return element informationtag_name = driver.execute_script("return arguments[0].tagName", button)// Pass WebElement as argumentconst button = await driver.findElement(By.id('submit'));await driver.executeScript('arguments[0].click()', button);
// Pass multiple argumentsconst input = await driver.findElement(By.id('name'));const value = 'John Doe';await driver.executeScript('arguments[0].value = arguments[1]', input, value);
// Pass various typesawait driver.executeScript( 'console.log(arguments[0], arguments[1], arguments[2])', 'string', 42, true);
// Return element informationconst tagName = await driver.executeScript('return arguments[0].tagName', button);IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Pass WebElement as argumentIWebElement button = driver.FindElement(By.Id("submit"));js.ExecuteScript("arguments[0].click()", button);
// Pass multiple argumentsIWebElement input = driver.FindElement(By.Id("name"));string value = "John Doe";js.ExecuteScript("arguments[0].value = arguments[1]", input, value);
// Pass various typesjs.ExecuteScript( "console.log(arguments[0], arguments[1], arguments[2])", "string", 42, true);
// Return element informationstring tagName = (string)js.ExecuteScript("return arguments[0].tagName", button);Scrolling
Scroll Operations
Selenium 3 & 4 Stable
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll to bottom of pagejs.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// Scroll to topjs.executeScript("window.scrollTo(0, 0)");
// Scroll by specific amountjs.executeScript("window.scrollBy(0, 500)"); // Down 500pxjs.executeScript("window.scrollBy(0, -200)"); // Up 200px
// Scroll element into viewWebElement element = driver.findElement(By.id("footer"));js.executeScript("arguments[0].scrollIntoView(true)", element);
// Scroll into view with optionsjs.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 pagedriver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
# Scroll to topdriver.execute_script("window.scrollTo(0, 0)")
# Scroll by specific amountdriver.execute_script("window.scrollBy(0, 500)") # Down 500pxdriver.execute_script("window.scrollBy(0, -200)") # Up 200px
# Scroll element into viewelement = driver.find_element(By.ID, "footer")driver.execute_script("arguments[0].scrollIntoView(true)", element)
# Scroll into view with optionsdriver.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 pageawait driver.executeScript('window.scrollTo(0, document.body.scrollHeight)');
// Scroll to topawait driver.executeScript('window.scrollTo(0, 0)');
// Scroll by specific amountawait driver.executeScript('window.scrollBy(0, 500)'); // Down 500pxawait driver.executeScript('window.scrollBy(0, -200)'); // Up 200px
// Scroll element into viewconst element = await driver.findElement(By.id('footer'));await driver.executeScript('arguments[0].scrollIntoView(true)', element);
// Scroll into view with optionsawait driver.executeScript( "arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})", element);IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Scroll to bottom of pagejs.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
// Scroll to topjs.ExecuteScript("window.scrollTo(0, 0)");
// Scroll by specific amountjs.ExecuteScript("window.scrollBy(0, 500)"); // Down 500pxjs.ExecuteScript("window.scrollBy(0, -200)"); // Up 200px
// Scroll element into viewIWebElement element = driver.FindElement(By.Id("footer"));js.ExecuteScript("arguments[0].scrollIntoView(true)", element);
// Scroll into view with optionsjs.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 overlayWebElement hiddenButton = driver.findElement(By.id("hidden-btn"));js.executeScript("arguments[0].click()", hiddenButton);
// Click at specific coordinatesjs.executeScript( "document.elementFromPoint(100, 200).click()");
// Trigger click eventjs.executeScript( "arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))", hiddenButton);# Element obscured by overlayhidden_button = driver.find_element(By.ID, "hidden-btn")driver.execute_script("arguments[0].click()", hidden_button)
# Click at specific coordinatesdriver.execute_script("document.elementFromPoint(100, 200).click()")
# Trigger click eventdriver.execute_script( "arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))", hidden_button)// Element obscured by overlayconst hiddenButton = await driver.findElement(By.id('hidden-btn'));await driver.executeScript('arguments[0].click()', hiddenButton);
// Click at specific coordinatesawait driver.executeScript('document.elementFromPoint(100, 200).click()');
// Trigger click eventawait driver.executeScript( "arguments[0].dispatchEvent(new MouseEvent('click', {bubbles: true}))", hiddenButton);IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Element obscured by overlayIWebElement hiddenButton = driver.FindElement(By.Id("hidden-btn"));js.ExecuteScript("arguments[0].click()", hiddenButton);
// Click at specific coordinatesjs.ExecuteScript("document.elementFromPoint(100, 200).click()");
// Trigger click eventjs.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 textjs.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 valuejs.executeScript( "arguments[0].dispatchEvent(new Event('input', {bubbles: true}))", input);
// Remove elementjs.executeScript("arguments[0].remove()", driver.findElement(By.id("annoying-popup")));
// Add/remove classjs.executeScript("arguments[0].classList.add('highlight')", input);js.executeScript("arguments[0].classList.remove('disabled')", input);
// Change stylejs.executeScript("arguments[0].style.border = '2px solid red'", input);
// Set attributejs.executeScript("arguments[0].setAttribute('data-test', 'value')", input);# Change element textdriver.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 valuedriver.execute_script( "arguments[0].dispatchEvent(new Event('input', {bubbles: true}))", input_field)
# Remove elementdriver.execute_script("arguments[0].remove()", driver.find_element(By.ID, "annoying-popup"))
# Add/remove classdriver.execute_script("arguments[0].classList.add('highlight')", input_field)driver.execute_script("arguments[0].classList.remove('disabled')", input_field)
# Change styledriver.execute_script("arguments[0].style.border = '2px solid red'", input_field)
# Set attributedriver.execute_script("arguments[0].setAttribute('data-test', 'value')", input_field)// Change element textawait 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 valueawait driver.executeScript( "arguments[0].dispatchEvent(new Event('input', {bubbles: true}))", input);
// Remove elementconst popup = await driver.findElement(By.id('annoying-popup'));await driver.executeScript('arguments[0].remove()', popup);
// Add/remove classawait driver.executeScript("arguments[0].classList.add('highlight')", input);
// Change styleawait driver.executeScript("arguments[0].style.border = '2px solid red'", input);IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
// Change element textjs.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 valuejs.ExecuteScript( "arguments[0].dispatchEvent(new Event('input', {bubbles: true}))", input);
// Remove elementjs.ExecuteScript("arguments[0].remove()", driver.FindElement(By.Id("annoying-popup")));
// Add/remove classjs.ExecuteScript("arguments[0].classList.add('highlight')", input);
// Change stylejs.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 readywait.until(driver -> js.executeScript("return document.readyState").equals("complete"));
// Wait for jQuery to finishwait.until(driver -> (Boolean) js.executeScript("return jQuery.active === 0"));
// Wait for Angularwait.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 DOMwait.until(driver -> js.executeScript( "return document.querySelector('#dynamic-content') !== null"));wait = WebDriverWait(driver, 30)
# Wait for document readywait.until(lambda d: d.execute_script("return document.readyState") == "complete")
# Wait for jQuery to finishwait.until(lambda d: d.execute_script("return jQuery.active === 0"))
# Wait for Angularwait.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 elementwait.until(lambda d: d.execute_script( "return document.querySelector('#dynamic-content') !== null"))// Wait for document readyawait driver.wait(async () => { return await driver.executeScript('return document.readyState') === 'complete';}, 30000);
// Wait for jQuery to finishawait driver.wait(async () => { return await driver.executeScript('return jQuery.active === 0');}, 30000);
// Custom conditionawait 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 readywait.Until(d => js.ExecuteScript("return document.readyState").Equals("complete"));
// Wait for jQuery to finishwait.Until(d => (bool)js.ExecuteScript("return jQuery.active === 0"));
// Custom conditionwait.Until(d => (bool)js.ExecuteScript( "return document.querySelector('#dynamic-content') !== null"));Common Use Cases
| Scenario | JS Solution |
|---|---|
| Element behind overlay | element.click() via JS |
| Scroll to element | scrollIntoView() |
| Set hidden input | element.value = x |
| Get computed style | getComputedStyle() |
| Trigger events | dispatchEvent() |
| Wait for framework | Check framework state |
Best Practices
- Use Selenium methods first - JS is a last resort
- Always trigger events when setting values programmatically
- Handle errors - JS exceptions don’t always surface cleanly
- Keep scripts simple - Complex JS is hard to debug
- Consider maintainability - JS bypasses normal user flow
Next Steps
- Shadow DOM - Access shadow DOM elements
- File Uploads - Handle file inputs
- Iframes Handling - Work with embedded frames
- Explicit Waits - Combine JS with proper waits
- Debugging Tips - Debug JavaScript issues