0
0
Selenium Javatesting~15 mins

Executing JavaScript in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Execute JavaScript to change page title and verify
Preconditions (2)
Step 1: Open the browser and navigate to https://example.com
Step 2: Use JavaScript to change the page title to 'New Title'
Step 3: Retrieve the page title using WebDriver
Step 4: Verify that the page title is 'New Title'
✅ Expected Result: The page title changes to 'New Title' and the verification passes
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify page title equals 'New Title'
Best Practices:
Use JavascriptExecutor interface to run JavaScript
Use explicit waits if needed before assertions
Use meaningful variable names
Close the browser after test
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Casting WebDriver to JavascriptExecutor without checking
Not waiting for the title to update before asserting
Hardcoding the path to chromedriver inside the code
Not closing the browser after test
Bonus Challenge

Now add data-driven testing to change the title to 3 different values and verify each

Show Hint