Skip to content

[馃悰 Bug]: [java] Unable to create a new browser window after closing the current active window#17882

Description

@ShaikhArib05

Description

When driver.switchTo().newWindow(WindowType.WINDOW) is called after closing the currently active browser window, Selenium throws a NoSuchWindowException instead of opening a new window.

The root cause appears to be that RemoteTargetLocator stores the current window handle before creating a new window. If the current window is closed, Selenium later attempts to switch back to this now-invalid handle as part of its recovery logic. Since the handle no longer exists, the operation fails and the WebDriver gets stuck, even though another browser window is still available.

Steps to Reproduce:

driver.switchTo().newWindow(WindowType.WINDOW);
driver.close(); // Close the current window
driver.switchTo().newWindow(WindowType.WINDOW); // Throws NoSuchWindowException

Expected Behavior:
A new browser window should be created successfully as long as there is at least one valid browser session remaining.

Actual Behavior:
Selenium attempts to switch back to a closed window handle, resulting in:

NoSuchWindowException: target window already closed

Reproducible Code

Alternate Solution

Instead of removing the existing try-catch block entirely, validate that the previously stored window handle is still active before switching back to it.

Proposed approach:

Store the original window handle.
If an exception occurs while creating the new window, retrieve the list of currently open window handles.
Switch back to the original handle only if it still exists.
Otherwise, either:
switch to any remaining valid window, or
allow the newly created window to remain the active context without attempting recovery.

Example logic:

String originalHandle = driver.getWindowHandle();

try {
    // Create a new window
} catch (Exception e) {
    if (driver.getWindowHandles().contains(originalHandle)) {
        driver.switchTo().window(originalHandle);
    } else if (!driver.getWindowHandles().isEmpty()) {
        driver.switchTo().window(driver.getWindowHandles().iterator().next());
    }
    throw e;
}

鈩癸笍 Last known working version: 4.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-needs-triagingA Selenium member will evaluate this soon!C-javaJava BindingsG-w3cRequires change to W3C SpecI-defectSomething is not working as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions