Execute JavaScript to change page title and verify
Preconditions (2)
✅ Expected Result: The page title changes to 'New Title' and the verification passes
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import static org.junit.jupiter.api.Assertions.assertEquals; public class ExecuteJavaScriptTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("document.title = 'New Title';"); // Wait until title is updated WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(5)); wait.until(ExpectedConditions.titleIs("New Title")); String title = driver.getTitle(); assertEquals("New Title", title, "Page title should be updated to 'New Title'"); System.out.println("Test passed: Title changed successfully."); } finally { driver.quit(); } } }
This test opens the browser and navigates to the example.com page.
It uses the JavascriptExecutor interface to run JavaScript that changes the page title to 'New Title'.
Then it waits explicitly until the title is updated to avoid timing issues.
Finally, it asserts that the title is exactly 'New Title' and prints a success message.
The driver.quit() in the finally block ensures the browser closes even if the test fails.
Now add data-driven testing to change the title to 3 different values and verify each
JavascriptExecutor in Selenium Java?JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title;");
System.out.println(title);document.title, which is the page's title as a string.JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();");arguments[0].click(); which requires a WebElement passed as an argument.scrollIntoView(true) called on the element.arguments[0].scrollIntoView(true); to scroll.Pass the test and this pattern moves unknown