Popular Searches
Popular Course Categories
Popular Courses

Switching Between Windows

Switching Between Windows

Handling Browser Components

<div class="selenium-notes">

<h1>Switching Between Windows in Selenium WebDriver</h1>

<p><strong>Switching Between Windows</strong> in Selenium WebDriver is the process of changing the current browser context from one browser window or tab to another during test execution. Modern web applications frequently open links, authentication pages, reports, payment pages, documentation, or external services in a new tab or window.</p>

<p>Selenium WebDriver identifies each open browser window or tab using a unique <strong>Window Handle</strong>. To work with another window, we first capture the available window handles and then use <strong>driver.switchTo().window()</strong> to move the WebDriver focus to the required window.</p>

<p>In Selenium, tabs and windows are handled through the same window-handle mechanism. Selenium's official documentation describes <strong>getWindowHandle()</strong> as the handle of the current window and <strong>getWindowHandles()</strong> as the set of handles for all open windows in the current WebDriver session. :contentReference[oaicite:0]{index=0}</p>

<p><strong>Selenium Training:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a></p>

<p><strong>Register for Course Demo:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></p>

<hr>

<h2>1. What is Switching Between Windows?</h2>

<p>Switching between windows means moving Selenium's control from the currently active browser context to another open browser tab or window.</p>

<p>For example, suppose an application has a login page and clicking a link opens a documentation page in a new tab:</p>

<pre><code>Main Window

     |

     | Click "Documentation"

     v

New Tab / Window

     |

     | Selenium switches control

     v

Validate Documentation Page

     |

     | Switch back

     v

Main Window</code></pre>

<p>Selenium does not automatically allow subsequent commands to target every newly opened window. The test must explicitly switch to the required window handle before interacting with elements in that context. :contentReference[oaicite:1]{index=1}</p>

<hr>

<h2>2. Why Window Switching is Required</h2>

<p>When a web application opens a new tab or window, Selenium needs to know which browsing context should receive the next command.</p>

<ul>

<li>The original page remains open.</li>

<li>A new tab or window may be created.</li>

<li>Selenium assigns a unique handle to each window.</li>

<li>The test captures the handles.</li>

<li>The test switches to the required handle.</li>

<li>Actions can then be performed in that window.</li>

<li>The test can switch back to the original window when required.</li>

</ul>

<hr>

<h2>3. Window Handle</h2>

<p>A <strong>window handle</strong> is a unique identifier associated with a browser window or tab within a WebDriver session.</p>

<p>In Java Selenium, the current window handle is represented by a <strong>String</strong>.</p>

<pre><code>String parentWindow = driver.getWindowHandle();</code></pre>

<p>The value is generated and managed by the WebDriver session. Test scripts should store handles rather than attempting to construct them manually.</p>

<hr>

<h2>4. getWindowHandle()</h2>

<p>The <strong>getWindowHandle()</strong> method returns the handle of the current browser window.</p>

<pre><code>String currentWindow = driver.getWindowHandle();

System.out.println("Current Window: " + currentWindow);</code></pre>

<p>Selenium's Java API specifies that this method returns the current window handle, which can later be used to switch back to that window. :contentReference[oaicite:2]{index=2}</p>

<hr>

<h2>5. getWindowHandles()</h2>

<p>The <strong>getWindowHandles()</strong> method returns a <strong>Set&lt;String&gt;</strong> containing the handles of all open browser windows or tabs belonging to the current WebDriver session.</p>

<pre><code>Set&lt;String&gt; allWindows = driver.getWindowHandles();

 

for (String window : allWindows) {

    System.out.println(window);

}</code></pre>

<p>Selenium's Java API defines this as a set of window handles that can be passed to <strong>switchTo()</strong> to change the current browsing context. :contentReference[oaicite:3]{index=3}</p>

<hr>

<h2>6. switchTo().window()</h2>

<p>The <strong>switchTo().window()</strong> method changes WebDriver's current browsing context to the specified window handle.</p>

<pre><code>driver.switchTo().window(windowHandle);</code></pre>

<p>After switching, commands such as <strong>findElement()</strong>, <strong>getTitle()</strong>, <strong>getCurrentUrl()</strong>, and other WebDriver operations are performed against the selected window.</p>

<hr>

<h2>7. Basic Window Switching Flow</h2>

<pre><code>Start Test

    |

    v

Open Parent Window

    |

    v

Store Parent Handle

    |

    v

Click Link / Button

    |

    v

New Window or Tab Opens

    |

    v

Get All Window Handles

    |

    v

Identify Target Window

    |

    v

Switch to Target Window

    |

    v

Perform Actions / Assertions

    |

    v

Close Target Window if Required

    |

    v

Switch Back to Parent

    |

    v

Continue Test

    |

    v

Quit Browser</code></pre>

<hr>

<h2>8. Basic Example of Switching Between Two Windows</h2>

<pre><code>String parentWindow = driver.getWindowHandle();

 

driver.findElement(By.linkText("Open New Window")).click();

 

Set&lt;String&gt; allWindows = driver.getWindowHandles();

 

for (String window : allWindows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

System.out.println(driver.getTitle());</code></pre>

<hr>

<h2>9. Complete Java Example</h2>

<pre><code>import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WindowSwitchExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

 

            driver.get("https://example.com");

 

            String parentWindow = driver.getWindowHandle();

 

            driver.findElement(By.linkText("Open New Window")).click();

 

            WebDriverWait wait = new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

            );

 

            wait.until(d -> d.getWindowHandles().size() &gt; 1);

 

            Set&lt;String&gt; allWindows = driver.getWindowHandles();

 

            for (String window : allWindows) {

 

                if (!window.equals(parentWindow)) {

 

                    driver.switchTo().window(window);

 

                    System.out.println(

                            "New Window Title: " + driver.getTitle()

                    );

 

                    break;

                }

            }

 

            driver.switchTo().window(parentWindow);

 

            System.out.println(

                    "Parent Window Title: " + driver.getTitle()

            );

 

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>10. Step-by-Step Window Switching Process</h2>

<h3>Step 1: Open the Parent Window</h3>

<pre><code>driver.get("https://example.com");</code></pre>

<h3>Step 2: Store the Parent Handle</h3>

<pre><code>String parentWindow = driver.getWindowHandle();</code></pre>

<h3>Step 3: Perform the Action that Opens Another Window</h3>

<pre><code>driver.findElement(By.linkText("Open New Window")).click();</code></pre>

<h3>Step 4: Wait for the New Window</h3>

<pre><code>wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);</code></pre>

<h3>Step 5: Get All Handles</h3>

<pre><code>Set&lt;String&gt; windows = driver.getWindowHandles();</code></pre>

<h3>Step 6: Find the Target Window</h3>

<pre><code>for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}</code></pre>

<h3>Step 7: Perform Actions</h3>

<pre><code>System.out.println(driver.getTitle());

System.out.println(driver.getCurrentUrl());</code></pre>

<h3>Step 8: Switch Back</h3>

<pre><code>driver.switchTo().window(parentWindow);</code></pre>

<hr>

<h2>11. Parent Window and Child Window</h2>

<p>The window from which the test starts is commonly called the <strong>parent window</strong>. A newly opened tab or window is commonly referred to as the <strong>child window</strong>.</p>

<pre><code>Parent Window

     |

     | Click

     v

Child Window

     |

     | Test actions

     v

Switch Back

     |

     v

Parent Window</code></pre>

<p>The terms parent and child are convenient for describing test flow. Technically, Selenium works with top-level browsing contexts identified by window handles.</p>

<hr>

<h2>12. Storing the Parent Window</h2>

<p>Always store the original handle before opening another window when the test needs to return to the original page.</p>

<pre><code>String parentWindow = driver.getWindowHandle();</code></pre>

<p>This makes the test independent of assumptions about the numerical position of the parent window.</p>

<hr>

<h2>13. Finding the New Window</h2>

<p>A common approach is to compare every current handle with the original handle.</p>

<pre><code>for (String window : driver.getWindowHandles()) {

 

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}</code></pre>

<p>This approach is useful when exactly one additional window is expected.</p>

<hr>

<h2>14. Why You Should Not Depend on Window Index</h2>

<p>A beginner-friendly example often converts the set to an array and accesses index <strong>1</strong>.</p>

<pre><code>Object[] windows = driver.getWindowHandles().toArray();

 

driver.switchTo().window((String) windows[1]);</code></pre>

<p>Although this can work for a simple two-window demonstration, robust tests should not generally depend on a particular handle position. A better strategy is to compare handles or identify the target window using a property such as its title, URL, or a unique element.</p>

<hr>

<h2>15. Switching Based on Window Title</h2>

<p>When several windows are open, you can switch through the available handles and inspect the title.</p>

<pre><code>for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (driver.getTitle().equals("Selenium Documentation")) {

        break;

    }

}</code></pre>

<p>This is useful when the target window has a predictable and unique title.</p>

<hr>

<h2>16. Switching Based on URL</h2>

<p>Another approach is to identify the target window using its current URL.</p>

<pre><code>for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (driver.getCurrentUrl().contains("/documentation")) {

        break;

    }

}</code></pre>

<p>URL matching can be useful when different windows have similar or recognizable URL patterns.</p>

<hr>

<h2>17. Switching Based on a Unique Element</h2>

<p>If the title or URL is not reliable, a unique element can be used to identify the required page.</p>

<pre><code>for (String window : driver.getWindowHandles()) {

 

    driver.switchTo().window(window);

 

    if (!driver.findElements(By.id("documentationHeading")).isEmpty()) {

        break;

    }

}</code></pre>

<p>This technique is useful when the target page contains a distinctive element that does not exist on the other pages.</p>

<hr>

<h2>18. Waiting for a New Window</h2>

<p>A new browser context may not appear immediately after clicking a link. Therefore, synchronization is important.</p>

<pre><code>WebDriverWait wait = new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

);

 

wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);</code></pre>

<p>Waiting for the expected number of windows is preferable to adding an arbitrary fixed delay.</p>

<hr>

<h2>19. Why Thread.sleep() Should Be Avoided</h2>

<p>A common beginner approach is:</p>

<pre><code>Thread.sleep(5000);</code></pre>

<p>This pauses execution for a fixed amount of time regardless of whether the new window has already appeared.</p>

<p>A condition-based wait is generally more appropriate:</p>

<pre><code>wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);</code></pre>

<ul>

<li>It waits for a condition.</li>

<li>It can continue as soon as the condition is satisfied.</li>

<li>It avoids unnecessary fixed delays.</li>

<li>It makes synchronization clearer.</li>

</ul>

<hr>

<h2>20. Switching Back to the Parent Window</h2>

<p>After completing actions in the child window, use the stored parent handle to return.</p>

<pre><code>driver.switchTo().window(parentWindow);</code></pre>

<p>This is one of the most important steps when a test continues interacting with the original page.</p>

<hr>

<h2>21. Closing the Child Window</h2>

<p>When the test is finished with the child window, it can be closed using <strong>driver.close()</strong>.</p>

<pre><code>driver.close();</code></pre>

<p>The Selenium Java API specifies that <strong>close()</strong> closes the current window; if it is the last open window, the browser session is also ended. :contentReference[oaicite:4]{index=4}</p>

<hr>

<h2>22. Close and Switch Back</h2>

<p>After closing the child window, switch back to a valid remaining window.</p>

<pre><code>driver.close();

driver.switchTo().window(parentWindow);</code></pre>

<p>Selenium's documentation specifically notes that after closing a window, the driver should be switched back to another valid window handle before continuing. Otherwise, a <strong>NoSuchWindowException</strong> can occur. :contentReference[oaicite:5]{index=5}</p>

<hr>

<h2>23. close() vs quit()</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th><th>Effect</th></tr>

<tr><td>close()</td><td>Closes current window/tab</td><td>Only current browsing context is closed</td></tr>

<tr><td>quit()</td><td>Ends WebDriver session</td><td>Closes all associated windows and ends the session</td></tr>

</table>

<p>Use <strong>close()</strong> when you intentionally want to close the current window while continuing with another open window. Use <strong>quit()</strong> at the end of the test to terminate the browser session. :contentReference[oaicite:6]{index=6}</p>

<hr>

<h2>24. Complete Example with Close and Return</h2>

<pre><code>String parentWindow = driver.getWindowHandle();

 

driver.findElement(By.linkText("Open New Window")).click();

 

WebDriverWait wait = new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

);

 

wait.until(d -&gt; d.getWindowHandles().size() == 2);

 

for (String window : driver.getWindowHandles()) {

 

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

System.out.println(driver.getTitle());

 

driver.close();

 

driver.switchTo().window(parentWindow);

 

System.out.println(driver.getTitle());</code></pre>

<hr>

<h2>25. Switching Between Three Windows</h2>

<p>Window switching is not limited to two windows. A test may have several tabs or windows open.</p>

<pre><code>String parent = driver.getWindowHandle();

 

driver.findElement(By.id("window1")).click();

driver.findElement(By.id("window2")).click();

 

Set&lt;String&gt; windows = driver.getWindowHandles();

 

System.out.println("Total Windows: " + windows.size());

 

for (String window : windows) {

    driver.switchTo().window(window);

    System.out.println("Title: " + driver.getTitle());

}</code></pre>

<hr>

<h2>26. Three-Window Flow</h2>

<pre><code>Window A

   |

   +----&gt; Window B

   |

   +----&gt; Window C

 

Test can switch:

A -&gt; B

B -&gt; C

C -&gt; A

A -&gt; C

B -&gt; A</code></pre>

<hr>

<h2>27. Switching from One Child to Another Child</h2>

<p>If multiple child windows exist, store or identify their handles and switch directly.</p>

<pre><code>driver.switchTo().window(windowA);

driver.switchTo().window(windowB);

driver.switchTo().window(parentWindow);</code></pre>

<p>Each call changes the current WebDriver browsing context.</p>

<hr>

<h2>28. Using a Map for Named Window Handles</h2>

<p>For complex automation frameworks, window handles can be stored with meaningful names.</p>

<pre><code>Map&lt;String, String&gt; windows = new HashMap&lt;&gt;();

 

windows.put("parent", parentWindow);

windows.put("report", reportWindow);

windows.put("documentation", documentationWindow);</code></pre>

<p>This makes the test code easier to understand than repeatedly working with anonymous handle variables.</p>

<hr>

<h2>29. Utility Method for Switching</h2>

<p>A reusable utility method can reduce duplicate window-switching code.</p>

<pre><code>public static void switchToWindow(

        WebDriver driver,

        String targetTitle) {

 

    for (String window : driver.getWindowHandles()) {

 

        driver.switchTo().window(window);

 

        if (driver.getTitle().equals(targetTitle)) {

            return;

        }

    }

 

    throw new RuntimeException(

            "Target window not found: " + targetTitle

    );

}</code></pre>

<p>Usage:</p>

<pre><code>switchToWindow(

        driver,

        "Selenium Documentation"

);</code></pre>

<hr>

<h2>30. Utility Method to Return to Parent</h2>

<pre><code>public static void switchToParent(

        WebDriver driver,

        String parentHandle) {

 

    driver.switchTo().window(parentHandle);

}</code></pre>

<hr>

<h2>31. Selenium 4: Creating a New Tab</h2>

<p>Selenium 4 provides an API for creating a new top-level browsing context and switching to it immediately.</p>

<pre><code>driver.switchTo().newWindow(WindowType.TAB);</code></pre>

<p>The Selenium documentation describes this operation as creating a new tab or window and focusing the new browsing context. :contentReference[oaicite:7]{index=7}</p>

<hr>

<h2>32. Selenium 4: Creating a New Window</h2>

<pre><code>driver.switchTo().newWindow(WindowType.WINDOW);</code></pre>

<p>Required import:</p>

<pre><code>import org.openqa.selenium.WindowType;</code></pre>

<p>Unlike a link that opens a new context, this command explicitly asks Selenium to create a new tab or window and switch to it.</p>

<hr>

<h2>33. New Tab Example</h2>

<pre><code>driver.get("https://example.com");

 

String parentWindow = driver.getWindowHandle();

 

driver.switchTo().newWindow(WindowType.TAB);

 

driver.get("https://www.selenium.dev/");

 

System.out.println(driver.getTitle());

 

driver.switchTo().window(parentWindow);

 

System.out.println("Returned to parent");</code></pre>

<hr>

<h2>34. New Window Example</h2>

<pre><code>driver.get("https://example.com");

 

String parentWindow = driver.getWindowHandle();

 

driver.switchTo().newWindow(WindowType.WINDOW);

 

driver.get("https://www.selenium.dev/");

 

System.out.println(driver.getCurrentUrl());

 

driver.switchTo().window(parentWindow);</code></pre>

<hr>

<h2>35. Tabs vs Windows</h2>

<p>From the WebDriver perspective, Selenium handles browser tabs and windows using window handles. The distinction is primarily how the browser presents the top-level browsing context to the user. :contentReference[oaicite:8]{index=8}</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Tab</th><th>Window</th></tr>

<tr><td>Window Handle</td><td>Yes</td><td>Yes</td></tr>

<tr><td>switchTo().window()</td><td>Yes</td><td>Yes</td></tr>

<tr><td>getWindowHandles()</td><td>Included</td><td>Included</td></tr>

<tr><td>Can be closed with close()</td><td>Yes</td><td>Yes</td></tr>

<tr><td>Selenium 4 new context</td><td>WindowType.TAB</td><td>WindowType.WINDOW</td></tr>

</table>

<hr>

<h2>36. Window Switching vs Frame Switching</h2>

<p>Window switching and frame switching are different operations.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Window Switching</th><th>Frame Switching</th></tr>

<tr><td>Moves between tabs/windows</td><td>Moves into an iframe</td></tr>

<tr><td>Uses window handles</td><td>Uses frame reference, name, index, or WebElement</td></tr>

<tr><td>Uses switchTo().window()</td><td>Uses switchTo().frame()</td></tr>

<tr><td>Top-level browsing context</td><td>Nested browsing context</td></tr>

</table>

<hr>

<h2>37. Window Switching vs Alert Switching</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Window</th><th>Alert</th></tr>

<tr><td>Uses window handle</td><td>Uses alert object</td></tr>

<tr><td>driver.switchTo().window(handle)</td><td>driver.switchTo().alert()</td></tr>

<tr><td>Represents browser tab/window</td><td>Represents JavaScript dialog</td></tr>

</table>

<hr>

<h2>38. Common Exception: NoSuchWindowException</h2>

<p><strong>NoSuchWindowException</strong> can occur when Selenium attempts to interact with a window that no longer exists or when the driver remains focused on a window that was already closed.</p>

<pre><code>driver.close();

 

// Incorrect if current context is now closed

driver.findElement(By.id("username")).sendKeys("admin");</code></pre>

<p>Correct approach:</p>

<pre><code>driver.close();

driver.switchTo().window(parentWindow);

 

driver.findElement(By.id("username"))

       .sendKeys("admin");</code></pre>

<hr>

<h2>39. Common Exception: TimeoutException</h2>

<p>If the expected new window does not appear within the configured wait period, a timeout may occur.</p>

<pre><code>wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);</code></pre>

<p>Possible causes include:</p>

<ul>

<li>The click did not work.</li>

<li>The target link was incorrect.</li>

<li>The application did not open a new context.</li>

<li>The application was slow.</li>

<li>The expected window count was incorrect.</li>

</ul>

<hr>

<h2>40. Common Exception: NoSuchElementException</h2>

<p>After switching to a window, the test may still search for an element that belongs to another page.</p>

<pre><code>driver.switchTo().window(childWindow);

 

driver.findElement(By.id("parentPageElement")).click();</code></pre>

<p>The locator may be correct but the element may not exist in the current browsing context. Verify the title, URL, and page content after switching.</p>

<hr>

<h2>41. Verify the Window After Switching</h2>

<p>After switching, it is good practice to verify that the driver is actually in the expected context.</p>

<pre><code>driver.switchTo().window(childWindow);

 

System.out.println("Handle: " + driver.getWindowHandle());

System.out.println("Title: " + driver.getTitle());

System.out.println("URL: " + driver.getCurrentUrl());</code></pre>

<hr>

<h2>42. Assertion After Window Switching</h2>

<p>In TestNG, assertions can verify that the expected page opened.</p>

<pre><code>Assert.assertEquals(

        driver.getTitle(),

        "Selenium Documentation"

);</code></pre>

<p>Required import:</p>

<pre><code>import org.testng.Assert;</code></pre>

<hr>

<h2>43. TestNG Example</h2>

<pre><code>import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class WindowTest {

 

    @Test

    public void switchBetweenWindows() {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com");

 

            String parentWindow = driver.getWindowHandle();

 

            driver.findElement(

                    By.linkText("Open New Window")

            ).click();

 

            WebDriverWait wait = new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

            );

 

            wait.until(d -&gt; d.getWindowHandles().size() == 2);

 

            Set&lt;String&gt; windows = driver.getWindowHandles();

 

            for (String window : windows) {

 

                if (!window.equals(parentWindow)) {

 

                    driver.switchTo().window(window);

 

                    Assert.assertNotNull(

                            driver.getTitle()

                    );

 

                    break;

                }

            }

 

            driver.switchTo().window(parentWindow);

 

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>44. Real-World Example: Product Details</h2>

<p>Consider an e-commerce website where clicking a product comparison link opens product information in a new tab.</p>

<pre><code>Parent Product Page

       |

       | Click Compare

       v

Product Details Tab

       |

       | Validate price/details

       v

Close Tab

       |

       v

Return to Product Page</code></pre>

<p>The automation can store the product page handle, switch to the new tab, validate the required information, close the tab, and return to the parent.</p>

<hr>

<h2>45. Real-World Example: Documentation Link</h2>

<p>A web application may open external documentation in a new tab.</p>

<pre><code>String parent = driver.getWindowHandle();

 

driver.findElement(By.linkText("Documentation")).click();

 

WebDriverWait wait = new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

);

 

wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);

 

for (String handle : driver.getWindowHandles()) {

 

    if (!handle.equals(parent)) {

        driver.switchTo().window(handle);

        break;

    }

}

 

Assert.assertTrue(

        driver.getTitle().contains("Documentation")

);

 

driver.close();

driver.switchTo().window(parent);</code></pre>

<hr>

<h2>46. Real-World Example: Reports</h2>

<p>Testing applications often open generated reports in a separate tab.</p>

<pre><code>Login Page

    |

    v

Dashboard

    |

    v

Generate Report

    |

    v

Report Tab

    |

    v

Validate Report

    |

    v

Close Report

    |

    v

Dashboard</code></pre>

<hr>

<h2>47. Real-World Example: Authentication Flow</h2>

<p>Some applications may open an authentication or identity-provider page in another tab or window. The automation should identify the new context, perform the required test actions, and return to the application context when appropriate.</p>

<p>The exact flow depends on the application's implementation and authentication architecture, so tests should identify the target context rather than assuming a fixed window position.</p>

<hr>

<h2>48. Handling Multiple Windows Using a Loop</h2>

<pre><code>Set&lt;String&gt; handles = driver.getWindowHandles();

 

for (String handle : handles) {

 

    driver.switchTo().window(handle);

 

    System.out.println(

            "Window Title: " + driver.getTitle()

    );

 

    System.out.println(

            "Window URL: " + driver.getCurrentUrl()

    );

}</code></pre>

<hr>

<h2>49. Finding a Window by Title</h2>

<pre><code>public static void switchToWindowByTitle(

        WebDriver driver,

        String expectedTitle) {

 

    for (String handle : driver.getWindowHandles()) {

 

        driver.switchTo().window(handle);

 

        if (driver.getTitle().equals(expectedTitle)) {

            return;

        }

    }

 

    throw new RuntimeException(

            "Window with title not found: " + expectedTitle

    );

}</code></pre>

<hr>

<h2>50. Finding a Window by URL</h2>

<pre><code>public static void switchToWindowByUrl(

        WebDriver driver,

        String expectedUrlPart) {

 

    for (String handle : driver.getWindowHandles()) {

 

        driver.switchTo().window(handle);

 

        if (driver.getCurrentUrl().contains(expectedUrlPart)) {

            return;

        }

    }

 

    throw new RuntimeException(

            "Window with URL pattern not found"

    );

}</code></pre>

<hr>

<h2>51. Page Object Model and Window Switching</h2>

<p>In a Page Object Model framework, window-switching logic can be placed inside a utility or base class rather than duplicating it in every page class.</p>

<pre><code>public class WindowUtils {

 

    public static String getCurrentWindow(

            WebDriver driver) {

 

        return driver.getWindowHandle();

    }

 

    public static void switchToWindow(

            WebDriver driver,

            String handle) {

 

        driver.switchTo().window(handle);

    }

}</code></pre>

<hr>

<h2>52. Window Switching Utility Class</h2>

<pre><code>import java.util.Set;

import org.openqa.selenium.WebDriver;

 

public class WindowUtils {

 

    public static String getParentHandle(

            WebDriver driver) {

 

        return driver.getWindowHandle();

    }

 

    public static Set&lt;String&gt; getAllHandles(

            WebDriver driver) {

 

        return driver.getWindowHandles();

    }

 

    public static void switchToHandle(

            WebDriver driver,

            String handle) {

 

        driver.switchTo().window(handle);

    }

 

    public static void switchToWindowByTitle(

            WebDriver driver,

            String title) {

 

        for (String handle : driver.getWindowHandles()) {

 

            driver.switchTo().window(handle);

 

            if (driver.getTitle().equals(title)) {

                return;

            }

        }

 

        throw new RuntimeException(

                "Window not found: " + title

        );

    }

}</code></pre>

<hr>

<h2>53. Best Practice: Store the Original Handle</h2>

<pre><code>String parentWindow = driver.getWindowHandle();</code></pre>

<p>Keeping the original handle makes returning to the starting page straightforward.</p>

<hr>

<h2>54. Best Practice: Wait for the Expected Window Count</h2>

<pre><code>wait.until(d -&gt; d.getWindowHandles().size() == 2);</code></pre>

<p>Do not immediately assume that the new context is already available.</p>

<hr>

<h2>55. Best Practice: Identify Windows Reliably</h2>

<p>Prefer meaningful conditions such as:</p>

<ul>

<li>Window title</li>

<li>Current URL</li>

<li>Unique page element</li>

<li>Difference between original and current handles</li>

</ul>

<p>Avoid hard-coded assumptions such as always selecting index <strong>1</strong> when the test can identify the target more reliably.</p>

<hr>

<h2>56. Best Practice: Verify After Switching</h2>

<pre><code>driver.switchTo().window(targetWindow);

 

Assert.assertEquals(

        driver.getTitle(),

        "Expected Title"

);</code></pre>

<p>Verification makes failures easier to diagnose.</p>

<hr>

<h2>57. Best Practice: Close Unused Windows</h2>

<p>Leaving unnecessary windows open can make later test steps difficult to manage.</p>

<pre><code>driver.close();

driver.switchTo().window(parentWindow);</code></pre>

<hr>

<h2>58. Best Practice: Use quit() in Cleanup</h2>

<p>At the end of the complete test or test suite, terminate the WebDriver session.</p>

<pre><code>driver.quit();</code></pre>

<p>This closes the associated browser contexts and ends the WebDriver session. :contentReference[oaicite:9]{index=9}</p>

<hr>

<h2>59. Common Mistakes in Window Switching</h2>

<ul>

<li>Not storing the parent window handle.</li>

<li>Trying to interact with a child page without switching to it.</li>

<li>Using a fixed delay instead of a condition-based wait.</li>

<li>Assuming window index 1 is always the required window.</li>

<li>Closing a window and then continuing without switching to a valid handle.</li>

<li>Confusing window switching with iframe switching.</li>

<li>Forgetting to close unnecessary windows.</li>

<li>Calling quit() too early.</li>

<li>Using a title that is not unique to identify the target.</li>

<li>Not validating the current URL or title after switching.</li>

</ul>

<hr>

<h2>60. Incorrect vs Correct Approach</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Incorrect / Fragile Approach</th><th>Better Approach</th></tr>

<tr><td>Always use windows[1]</td><td>Identify the required handle</td></tr>

<tr><td>Use Thread.sleep()</td><td>Use explicit/condition-based waiting</td></tr>

<tr><td>Forget the parent handle</td><td>Store getWindowHandle()</td></tr>

<tr><td>Interact immediately after opening</td><td>Wait for the new context</td></tr>

<tr><td>Close child and continue</td><td>Close child and switch to parent</td></tr>

<tr><td>Assume title without validation</td><td>Verify title or URL</td></tr>

</table>

<hr>

<h2>61. Practical Mini Project: Documentation Window</h2>

<p><strong>Objective:</strong> Automate a scenario where clicking a documentation link opens a new window.</p>

<h3>Test Steps</h3>

<ol>

<li>Launch Chrome.</li>

<li>Open the application.</li>

<li>Store the current window handle.</li>

<li>Click the documentation link.</li>

<li>Wait until a second window appears.</li>

<li>Collect all window handles.</li>

<li>Identify the new window.</li>

<li>Switch to the new window.</li>

<li>Verify title or URL.</li>

<li>Perform required validation.</li>

<li>Close the documentation window.</li>

<li>Switch back to the original application window.</li>

<li>Continue the test.</li>

<li>Quit WebDriver.</li>

</ol>

<hr>

<h2>62. Practical Project Code</h2>

<pre><code>import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

 

public class DocumentationWindowTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://example.com");

 

            String parentWindow =

                    driver.getWindowHandle();

 

            driver.findElement(

                    By.linkText("Documentation")

            ).click();

 

            WebDriverWait wait =

                    new WebDriverWait(

                            driver,

                            Duration.ofSeconds(10)

                    );

 

            wait.until(

                    d -&gt; d.getWindowHandles().size() &gt; 1

            );

 

            for (String handle :

                    driver.getWindowHandles()) {

 

                if (!handle.equals(parentWindow)) {

 

                    driver.switchTo().window(handle);

 

                    Assert.assertTrue(

                            driver.getTitle()

                                    .contains("Documentation")

                    );

 

                    driver.close();

 

                    break;

                }

            }

 

            driver.switchTo().window(parentWindow);

 

            System.out.println(

                    "Returned to application"

            );

 

        } finally {

 

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>63. Debugging Window Switching</h2>

<p>When a window-switching test fails, print all available handles, titles, and URLs.</p>

<pre><code>for (String handle : driver.getWindowHandles()) {

 

    driver.switchTo().window(handle);

 

    System.out.println(

            "Handle: " + handle

    );

 

    System.out.println(

            "Title: " + driver.getTitle()

    );

 

    System.out.println(

            "URL: " + driver.getCurrentUrl()

    );

 

    System.out.println("--------------------");

}</code></pre>

<p>This is especially useful when several windows are open.</p>

<hr>

<h2>64. Window Switching Debug Flow</h2>

<pre><code>Test Fails

    |

    v

Print Window Count

    |

    v

Print All Handles

    |

    v

Print Titles

    |

    v

Print URLs

    |

    v

Identify Target Context

    |

    v

Verify Switch

    |

    v

Check Locator

    |

    v

Check Wait Condition

    |

    v

Run Test Again</code></pre>

<hr>

<h2>65. Important Selenium Methods</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th></tr>

<tr><td>getWindowHandle()</td><td>Returns the current window handle</td></tr>

<tr><td>getWindowHandles()</td><td>Returns handles of all open windows/tabs</td></tr>

<tr><td>switchTo().window(handle)</td><td>Switches to a specified window</td></tr>

<tr><td>switchTo().newWindow(WindowType.TAB)</td><td>Creates and switches to a new tab</td></tr>

<tr><td>switchTo().newWindow(WindowType.WINDOW)</td><td>Creates and switches to a new window</td></tr>

<tr><td>close()</td><td>Closes the current window/tab</td></tr>

<tr><td>quit()</td><td>Closes all associated windows and ends the session</td></tr>

</table>

<hr>

<h2>66. Window Switching Cheat Sheet</h2>

<pre><code>// Current window

String parent = driver.getWindowHandle();

 

// All windows

Set&lt;String&gt; windows = driver.getWindowHandles();

 

// Switch

driver.switchTo().window(handle);

 

// Create new tab

driver.switchTo().newWindow(WindowType.TAB);

 

// Create new window

driver.switchTo().newWindow(WindowType.WINDOW);

 

// Close current

driver.close();

 

// Return to parent

driver.switchTo().window(parent);

 

// End session

driver.quit();</code></pre>

<hr>

<h2>67. Interview Question: What is Window Switching?</h2>

<p><strong>Answer:</strong> Window switching is the process of changing WebDriver's current browsing context from one browser tab or window to another using window handles.</p>

<hr>

<h2>68. Interview Question: What is getWindowHandle()?</h2>

<p><strong>Answer:</strong> <strong>getWindowHandle()</strong> returns the unique handle of the current browser window or tab within the WebDriver session.</p>

<hr>

<h2>69. Interview Question: What is getWindowHandles()?</h2>

<p><strong>Answer:</strong> <strong>getWindowHandles()</strong> returns a set containing the handles of all currently available browser windows or tabs in the WebDriver session.</p>

<hr>

<h2>70. Interview Question: How do you switch to another window?</h2>

<p><strong>Answer:</strong> First obtain the target window handle and then use:</p>

<pre><code>driver.switchTo().window(targetHandle);</code></pre>

<hr>

<h2>71. Interview Question: How do you switch back to the parent window?</h2>

<p><strong>Answer:</strong> Store the parent handle before opening the child window and use that handle later.</p>

<pre><code>String parent = driver.getWindowHandle();

 

driver.switchTo().window(parent);</code></pre>

<hr>

<h2>72. Interview Question: Difference Between close() and quit()?</h2>

<p><strong>Answer:</strong> <strong>close()</strong> closes the current browser context, while <strong>quit()</strong> ends the WebDriver session and closes the associated browser windows.</p>

<hr>

<h2>73. Interview Question: How can you identify a specific window?</h2>

<p><strong>Answer:</strong> A window can be identified using its handle, title, URL, or a unique element on the target page. For reliable automation, use a property that uniquely identifies the intended context.</p>

<hr>

<h2>74. Interview Question: Why should Thread.sleep() be avoided?</h2>

<p><strong>Answer:</strong> Thread.sleep() uses a fixed delay. The test may wait longer than necessary or may continue too early if the required condition takes longer. Condition-based waits synchronize the test with the actual application state.</p>

<hr>

<h2>75. Interview Question: What happens if you close the current window and do not switch?</h2>

<p><strong>Answer:</strong> If the current browsing context has been closed, continuing to issue commands against it can result in <strong>NoSuchWindowException</strong>. The test should switch to another valid window handle after closing the current one. :contentReference[oaicite:10]{index=10}</p>

<hr>

<h2>76. Interview Question: Can Selenium switch between tabs?</h2>

<p><strong>Answer:</strong> Yes. Selenium handles browser tabs and windows through window handles. The same <strong>switchTo().window()</strong> mechanism can be used for either. :contentReference[oaicite:11]{index=11}</p>

<hr>

<h2>77. Interview Question: How do you create a new tab in Selenium 4?</h2>

<p><strong>Answer:</strong> Selenium 4 provides:</p>

<pre><code>driver.switchTo().newWindow(WindowType.TAB);</code></pre>

<hr>

<h2>78. Interview Question: How do you create a new browser window in Selenium 4?</h2>

<p><strong>Answer:</strong></p>

<pre><code>driver.switchTo().newWindow(WindowType.WINDOW);</code></pre>

<hr>

<h2>79. Important Points to Remember</h2>

<ul>

<li>Every top-level browser window/tab has a window handle.</li>

<li>Use getWindowHandle() for the current context.</li>

<li>Use getWindowHandles() for all open contexts.</li>

<li>Use switchTo().window() to change the current context.</li>

<li>Store the parent handle before opening a new context.</li>

<li>Wait for the new window before switching.</li>

<li>Do not blindly depend on a window index in robust tests.</li>

<li>Use title, URL, or a unique element when necessary.</li>

<li>After closing a child window, switch to a valid remaining window.</li>

<li>Use quit() for final WebDriver cleanup.</li>

</ul>

<hr>

<h2>80. Window Switching Checklist</h2>

<ul>

<li>☐ Open the application.</li>

<li>☐ Store the parent window handle.</li>

<li>☐ Perform the action that opens the new tab/window.</li>

<li>☐ Wait for the expected number of windows.</li>

<li>☐ Get all window handles.</li>

<li>☐ Identify the required handle.</li>

<li>☐ Switch to the target window.</li>

<li>☐ Verify title or URL.</li>

<li>☐ Perform required actions.</li>

<li>☐ Close the child window if required.</li>

<li>☐ Switch back to the parent window.</li>

<li>☐ Continue the test.</li>

<li>☐ Quit the WebDriver session during cleanup.</li>

</ul>

<hr>

<h2>81. Best Practices Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Parent Handle</td><td>Store it before opening another window</td></tr>

<tr><td>Synchronization</td><td>Wait for the expected window condition</td></tr>

<tr><td>Identification</td><td>Use handle, title, URL, or unique element</td></tr>

<tr><td>Window Index</td><td>Avoid depending on fixed indexes in robust tests</td></tr>

<tr><td>Closing</td><td>Close only the window that is no longer required</td></tr>

<tr><td>After Close</td><td>Switch to a valid remaining handle</td></tr>

<tr><td>Verification</td><td>Validate title, URL, or page element</td></tr>

<tr><td>Cleanup</td><td>Use quit() after the test/session</td></tr>

<tr><td>Framework</td><td>Move reusable switching logic into utilities</td></tr>

</table>

<hr>

<h2>82. Final Example</h2>

<pre><code>import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class CompleteWindowSwitching {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://example.com");

 

            String parentWindow =

                    driver.getWindowHandle();

 

            driver.findElement(

                    By.linkText("Open New Window")

            ).click();

 

            WebDriverWait wait =

                    new WebDriverWait(

                            driver,

                            Duration.ofSeconds(10)

                    );

 

            wait.until(

                    d -&gt; d.getWindowHandles().size() &gt; 1

            );

 

            Set&lt;String&gt; handles =

                    driver.getWindowHandles();

 

            String childWindow = null;

 

            for (String handle : handles) {

 

                if (!handle.equals(parentWindow)) {

 

                    childWindow = handle;

                    break;

                }

            }

 

            if (childWindow != null) {

 

                driver.switchTo().window(childWindow);

 

                System.out.println(

                        "Child Title: " +

                        driver.getTitle()

                );

 

                System.out.println(

                        "Child URL: " +

                        driver.getCurrentUrl()

                );

 

                driver.close();

            }

 

            driver.switchTo().window(parentWindow);

 

            System.out.println(

                    "Parent Title: " +

                    driver.getTitle()

            );

 

        } finally {

 

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>83. Quick Revision</h2>

<pre><code>1. Store parent handle:

   String parent = driver.getWindowHandle();

 

2. Open another window/tab.

 

3. Wait for new window:

   wait.until(d -&gt; d.getWindowHandles().size() &gt; 1);

 

4. Get all handles:

   Set&lt;String&gt; handles = driver.getWindowHandles();

 

5. Find target handle.

 

6. Switch:

   driver.switchTo().window(target);

 

7. Perform actions/assertions.

 

8. Close if required:

   driver.close();

 

9. Switch back:

   driver.switchTo().window(parent);

 

10. End session:

    driver.quit();</code></pre>

<hr>

<h2>84. Course Resources</h2>

<p>To learn Selenium WebDriver, browser automation, window handling, locators, synchronization, Page Object Model, TestNG, automation frameworks, and practical testing, explore the Selenium training resources below.</p>

<ul>

<li><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy Selenium Training Course</a></li>

<li><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></li>

</ul>

<hr>

<h2>85. Conclusion</h2>

<p>Switching Between Windows is an important Selenium WebDriver skill for automating applications that use multiple browser tabs or windows. The core workflow is to store the current window handle, wait for a new context when necessary, obtain all available handles, identify the required window, switch using <strong>driver.switchTo().window()</strong>, perform the required actions, and finally return to a valid window or close the unused context.</p>

<p>For reliable automation, avoid unnecessary fixed delays and avoid blindly depending on window indexes. Instead, use explicit conditions and identify the target context through its handle, title, URL, or a unique page element. Selenium's official documentation provides the same fundamental window-handle and switching model for tabs and windows. :contentReference[oaicite:12]{index=12}</p>

<p><strong>Recommended Selenium Course:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Learn Selenium WebDriver with JustAcademy</a></p>

<p><strong>Course Demo:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

</div>

Previous Next
whatsapp