Sometimes, Selenium cannot perform certain actions directly. Executing JavaScript helps control the browser in ways Selenium alone cannot.
Executing JavaScript in 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.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello from JavaScript!')");JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, 500);");JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = driver.findElement(By.id("myElement")); js.executeScript("arguments[0].style.border='3px solid red';", element);
This test opens a webpage, scrolls down, highlights the main heading by changing its background color, and prints the page title using JavaScript execution.
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(); } } }
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.
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.
Practice
JavascriptExecutor in Selenium Java?Solution
Step 1: Understand the role of JavascriptExecutor
JavascriptExecutor allows running JavaScript code inside the browser from Selenium tests.Step 2: Identify the main use case
It is mainly used to perform actions or retrieve information that Selenium WebDriver cannot do directly.Final Answer:
To execute JavaScript code directly in the browser during a test -> Option BQuick Check:
JavascriptExecutor runs JS code in browser [OK]
- Confusing JavascriptExecutor with element locators
- Thinking it starts WebDriver sessions
- Assuming it generates reports
Solution
Step 1: Recall the casting syntax in Java
To use JavascriptExecutor, you cast the WebDriver instance like this: (JavascriptExecutor) driver.Step 2: Check each option
JavascriptExecutor js = (JavascriptExecutor) driver; uses correct casting syntax. The other options are invalid method calls or constructors.Final Answer:
JavascriptExecutor js = (JavascriptExecutor) driver; -> Option DQuick Check:
Cast driver to JavascriptExecutor using (JavascriptExecutor) [OK]
- Using non-existent methods like getJavascriptExecutor()
- Trying to instantiate JavascriptExecutor with new keyword
- Calling executeScript() without casting
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title;");
System.out.println(title);Solution
Step 1: Understand the JavaScript executed
The script returnsdocument.title, which is the page's title as a string.Step 2: Check the casting and output
The returned object is cast to String and printed, so it outputs the page title.Final Answer:
Prints the current page's title -> Option AQuick Check:
executeScript returns document.title string [OK]
- Expecting URL instead of title
- Not casting return value to String
- Confusing output with undefined or errors
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();");Solution
Step 1: Analyze the executeScript call
The script usesarguments[0].click();which requires a WebElement passed as an argument.Step 2: Check the method call parameters
No WebElement is passed to executeScript, so it will fail at runtime.Final Answer:
Missing WebElement argument to click() -> Option CQuick Check:
arguments[0] needs a WebElement passed [OK]
- Forgetting to pass WebElement argument
- Assuming casting is wrong
- Thinking executeScript method is missing
Solution
Step 1: Recall JavaScript method to scroll to element
The correct JS method isscrollIntoView(true)called on the element.Step 2: Check the Selenium executeScript usage
Pass the WebElement as an argument and usearguments[0].scrollIntoView(true);to scroll.Final Answer:
js.executeScript("arguments[0].scrollIntoView(true);", element); -> Option AQuick Check:
Use scrollIntoView with element argument [OK]
- Using window.scrollTo with element (invalid)
- Calling non-existent scrollToElement function
- Not passing element as argument
Ready to prove it?
Pass the test and this pattern moves unknown
