Sometimes, Selenium cannot perform certain actions directly. Executing JavaScript helps control the browser in ways Selenium alone cannot.
0
0
Executing JavaScript in Selenium Java
Introduction
When clicking a button that Selenium's click() cannot reach.
To scroll the page to a specific position.
To get or set values of elements not accessible by Selenium methods.
To change the style or attributes of elements dynamically during tests.
To trigger browser alerts or confirm dialogs.
Syntax
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript code here");You must cast the WebDriver instance to JavascriptExecutor.
The executeScript method runs JavaScript code in the browser context.
Examples
This example shows how to display a browser alert using JavaScript.
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello from JavaScript!')");This scrolls the page down by 500 pixels vertically.
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, 500);");This adds a red border around a specific element to highlight it.
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = driver.findElement(By.id("myElement")); js.executeScript("arguments[0].style.border='3px solid red';", element);
Sample Program
This test opens a webpage, scrolls down, highlights the main heading by changing its background color, and prints the page title using JavaScript execution.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ExecuteJavaScriptExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.example.com"); JavascriptExecutor js = (JavascriptExecutor) driver; // Scroll down 300 pixels js.executeScript("window.scrollBy(0,300);"); // Find element and highlight it WebElement heading = driver.findElement(By.tagName("h1")); js.executeScript("arguments[0].style.backgroundColor = 'yellow';", heading); // Get page title using JavaScript String title = (String) js.executeScript("return document.title;"); System.out.println("Page title is: " + title); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Always cast your WebDriver to JavascriptExecutor before running JavaScript.
Use arguments[0], arguments[1], etc., to pass WebElements or values safely into the script.
Be careful with JavaScript code syntax; errors can cause test failures.
Summary
Executing JavaScript lets you do things Selenium cannot do directly.
Use JavascriptExecutor and executeScript() method to run JavaScript in the browser.
Pass WebElements as arguments to manipulate page elements safely.