Operations 9 min read

Mastering Selenium’s JavaScriptExecutor: Real‑World Login Automation and Async Scrolling

Explore two hands‑on Selenium WebDriver examples that leverage JavaScriptExecutor to automate a login flow with visual element highlighting, retrieve page metadata, and perform asynchronous scrolling, while learning practical code snippets, execution tips, and troubleshooting strategies for robust web UI testing.

FunTester
FunTester
FunTester
Mastering Selenium’s JavaScriptExecutor: Real‑World Login Automation and Async Scrolling

Practical Login Automation with JavaScriptExecutor

This example demonstrates how to automate a typical login scenario on the LambdaTest e‑commerce demo site using Selenium WebDriver combined with JavascriptExecutor. The test highlights input fields, enters credentials, clicks the login button via JavaScript, and extracts page information such as title and domain.

Navigate to the account login page.

Highlight the email and password fields with a red border, input test data, then restore the original style.

Highlight the login button and trigger a JavaScript click to avoid element‑click failures.

Retrieve the page title and domain using JavaScript for fast access.

Verify that the login succeeded by asserting the presence of the "My Account" header.

public class TestJavaScriptExecutor {
    private WebDriver driver;

    @BeforeTest
    public void setup() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
    }

    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}
@Test
public void testJavaScriptExecutorCommand() {
    driver.get("https://***/index.php?route=account/login");
    JavascriptExecutor js = (JavascriptExecutor) driver;

    WebElement emailAddressField = driver.findElement(By.id("input-email"));
    js.executeScript("arguments[0].style.border='3px solid red'", emailAddressField);
    emailAddressField.sendKeys("[email protected]");
    js.executeScript("arguments[0].style.border='2px solid #ced4da'", emailAddressField);

    WebElement passwordField = driver.findElement(By.id("input-password"));
    js.executeScript("arguments[0].style.border='3px solid red'", passwordField);
    passwordField.sendKeys("FunTester123");
    js.executeScript("arguments[0].style.border='2px solid #ced4da'", passwordField);

    WebElement loginBtn = driver.findElement(By.cssSelector("input.btn"));
    js.executeScript("arguments[0].style.border='3px solid red'", loginBtn);
    js.executeScript("arguments[0].click();", loginBtn);

    String titleText = js.executeScript("return document.title;").toString();
    System.out.println("Page Title is: " + titleText);
    String domainName = js.executeScript("return document.domain;").toString();
    System.out.println("Domain is: " + domainName);

    String myAccountHeader = driver.findElement(By.cssSelector("#content h2")).getText();
    assertEquals(myAccountHeader, "My Account");
}

Asynchronous Scrolling Example

The following test shows how to scroll to the bottom of a page using executeAsyncScript, which provides precise control over asynchronous operations such as scrolling, animations, or AJAX calls.

@Test
public void testExecuteAsyncScript() {
    driver.get("https://ecommerce-playground.lambdatest.io");
    JavascriptExecutor js = (JavascriptExecutor) driver;

    js.executeAsyncScript(
        "var callback = arguments[arguments.length - 1];" +
        "window.scrollBy(0, document.body.scrollHeight);" +
        "callback();"
    );

    String fromTheBlogText = driver.findElement(By.cssSelector("#entry_217991 > h3")).getText();
    assertEquals(fromTheBlogText, "FROM THE BLOG");
}

Key Techniques and Tips

Visual feedback : Highlight elements with a red border using JavaScript to make test execution steps obvious during debugging.

JavaScript click : Directly invoke element.click() via JavaScript to bypass issues where the standard WebDriver click fails (e.g., element hidden or overlapped).

Fast page information : Retrieve document.title, document.domain, or document.URL through JavaScript for immediate access, avoiding extra WebDriver calls.

Asynchronous control : Use executeAsyncScript with an explicit callback() to ensure the script finishes before the test proceeds, preventing race conditions.

Scrolling utilities : Demonstrated scrolling to an element, scrolling by a fixed offset, and scrolling to the page bottom with simple JavaScript snippets.

Common Issues and Solutions

Element click does not work

Symptom : element.click() fails to trigger the action.

Solution : Use JavaScript to force the click:

js.executeScript("arguments[0].click();", element);

Page does not scroll to the target element

Symptom : The element is outside the viewport, causing subsequent actions to fail.

Solution : Scroll the element into view first:

js.executeScript("arguments[0].scrollIntoView(true);", element);

Asynchronous timing problems

Symptom : Operations execute too early or too late, leading to flaky tests.

Solution : Wrap the asynchronous work in executeAsyncScript and call the provided callback when the operation completes.

Conclusion

These two hands‑on cases illustrate the power and flexibility of Selenium’s JavascriptExecutor. By combining synchronous and asynchronous JavaScript calls, testers can achieve reliable element interaction, visual debugging, and efficient page data extraction, making UI automation more robust and maintainable.

JavaAutomationTestingseleniumwebdriverAsyncScriptJavaScriptExecutor
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.