Open In App

How to handle multiple windows in Selenium?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Handling multiple windows in Selenium is crucial when dealing with web applications that open new tabs or windows during interactions. Whether you’re testing applications with pop-ups, modals, or new browser tabs, Selenium WebDriver provides efficient methods to switch between multiple windows or tabs.

This functionality allows for comprehensive testing of all parts of a web application, ensuring that the user experience remains seamless across different browser contexts..

What is a Window Handle?

It is used to contain the address of all the windows. Consider it as a pointer to a window that yields a value in string data type. The handle for the window will be unique for each browser. The existence meaning for this function of the window retrieves all window handles.

Syntax

  • get.windowhandle(): It is used to return the handle of the currently active window.
  • get.windowhandles() : This method is used to get the handle of all opened windows.
  • set: It will set the window handles in the form of string. set<string> set= driver.get.windowhandles();
  • switch to: This function is used to switch between the windows.
  • action: This methods helps to do actions to windows.

Handling Multiple Windows in Selenium using Window Handles

Handling multiple windows in Selenium is done using window handles. One navigates between several browser tabs or windows. Here’s how:

  1. Open New Window/Tabs: When a link or button is clicked, execute actions that will open any window or tab.
  2. Get current window handle: Save the handle of the current window so that you can switch back. You can do this by calling driver.getWindowHandle().
  3. Get All Window Handles: It returns a set of handles of all opened windows or tabs using the driver.getWindowHandles().
  4. New Window: This will loop through all window handles identifying which handle is not the current handle. It then switches to that window by using driver.switchTo().window(handle).
  5. Perform actions: Upon change, perform actions in the new window or tab as required.
  6. Close Window: Closes currently active window if needed using driver.close().
  7. Switch Back: Your saved handle is to be used for switching back to the original window.

Steps to handle multiple windows in Selenium

  1. Visit the official site of geeksforgeeks.org
  2. Click on courses at GeeksforGeeks from quick links     
  3. Select a particular course ( Open with a new window )
  4. Click on the element of the new window 

Expected Result: It should click on the element of the new window

Implementation

Program 1: Click on the element of the new window  without shifting the focus of selenium

Java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFGWindowHandling {

    public static void main(String[] args) throws InterruptedException
    {
        // we are using chrome driver
        System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // entering the URL
        driver.get("https:// www.geeksforgeeks.org/");

        // to maximize the window
        driver.manage().window().maximize();

        // to delete all cookies
        driver.manage().deleteAllCookies();

        // to Scroll the screen to locate element
        JavascriptExecutor je = (JavascriptExecutor)driver;
        je.executeScript("window.scrollBy(0, 200)");
        driver.findElement(By.xpath("(// span
                
)[2]"</span><span class=p>)).</span><span class=na>click</span><span class=p>();</span>
 
<span class=w>        </span><span class=c1>// to select a particular course</span>
<span class=w>        </span><span class=n>Thread</span><span class=p>.</span><span class=na>sleep</span><span class=p>(</span><span class=mi>2000</span><span class=p>);</span>
<span class=w>        </span><span class=n>driver</span><span class=p>.</span><span class=na>findElement</span><span class=p>(</span><span class=n>By</span><span class=p>.</span><span class=na>xpath</span><span class=p>(</span><span class=s>"(// h4[text()='Data Structures and Algorithms - Self Paced'])[1]"</span><span class=p>)).</span><span class=na>click</span><span class=p>();</span>
 
<span class=w>        </span><span class=c1>// it will open with new tab</span>
 
<span class=w>        </span><span class=c1>// to click on (Read more here) on new window</span>
<span class=w>        </span><span class=n>driver</span><span class=p>.</span><span class=na>findElement</span><span class=p>(</span><span class=n>By</span><span class=p>.</span><span class=na>xpath</span><span class=p>(</span><span class=s>"(// a[text()='(Read more here)'])[1]"</span><span class=p>)).</span><span class=na>click</span><span class=p>();</span>
 
<span class=w>        </span><span class=c1>// statement to understand that operation is performed on new window</span>
<span class=w>        </span><span class=n>System</span><span class=p>.</span><span class=na>out</span><span class=p>.</span><span class=na>println</span><span class=p>(</span><span class=s>"operation is performed on new window"</span><span class=p>);</span>
<span class=w>    </span><span class=p>}</span>
<span class=p>}</span>
</pre></div></code>
</gfg-panel></gfg-tabs><p dir="ltr"><b><strong>Console Output:</strong></b></p>
<img src="https://media.geeksforgeeks.org/wp-content/uploads/20220623212343/WindowHEr1.JPG" alt="Console Output" width="inherit" height="inherit">output<blockquote><p dir="ltr"><span>org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath", "selector":"(//a

                    
)[1]"}

This exception is because when we click on a particular course new window (child window) is open and when we try to click on Read more here, at that time focus of selenium is on the main window (parent window). So we will use some method to shift the focus of selenium from one window to another.

Syntax: 

driver.switchTo().window(ID);

Where ID: ID of a particular window on which you need the change the focus of selenium.

To get the ID of Windows we will use the following method. 

  • driver.getWindowHandle(): To get the ID of the parent window (main window)
  • driver.getWindowHandles(): To get the ID of child windows (new window)

Let's observe how the IDs of two different windows are different,

Program 2: To get the IDs of different windows

Java
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFGIDsOfWindows {

    public static void main(String[] args) throws InterruptedException
    {
        // we are using chrome driver
        System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // entering the URL
        driver.get("https:// www.geeksforgeeks.org/");

        // to maximize the window
        driver.manage().window().maximize();

        // to delete all cookies
        driver.manage().deleteAllCookies();

        // to Scroll the screen to locate element
        JavascriptExecutor je = (JavascriptExecutor)driver;
        je.executeScript("window.scrollBy(0, 200)");
        driver.findElement(By.xpath("(// span)[2]")).click();

        // to select a particular course
        Thread.sleep(2000);
        driver.findElement(By.xpath("(// h4)[1]")).click();

        // it will open with new tab

        // getWindowHandle method to get ID of main window(parent window)
        String Parent_id = driver.getWindowHandle();
        System.out.println(Parent_id);

        // getWindowHandle method to get ID of new window (child window)
        Set<String> Child_id = driver.getWindowHandles();

        // for each loop
        for (String a : Child_id) {
            // it will print IDs of both window
            System.out.println(a);
        }
    }
}

Console Output:

Console Output

Here you can observe the IDs of windows are different.

CDwindow-EA925E71098EEFBB80858BE787CED1A5  (ID of main window)
CDwindow-C9078346729F1D0CF8AF12E938CE49DD (ID of new window)

So to change the focus of selenium from one window to another window we will use For each loop and provide the if-else condition. For each loop 

for( Datatype variable : collection )
{
Statements;
}

Program 3: Click on the element of the new window by shifting the focus of selenium

Java
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GFGWindowHandlingEx {

    public static void main(String[] args) throws InterruptedException
    {
        // we are using chrome driver
        System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // entering the URL
        driver.get("https:// www.geeksforgeeks.org/");

        // to maximize the window
        driver.manage().window().maximize();

        // to delete all cookies
        driver.manage().deleteAllCookies();

        // to Scroll the screen to locate element
        JavascriptExecutor je = (JavascriptExecutor)driver;
        je.executeScript("window.scrollBy(0, 200)");
        driver.findElement(By.xpath("(// span)[2]")).click();

        // to select a particular course
        Thread.sleep(2000);
        driver.findElement(By.xpath("(// h4)[1]")).click();

        // it will open with new tab

        // getWindowHandle method to get ID of main window(parent window)
        String Parent_id = driver.getWindowHandle();
        System.out.println(Parent_id);

        // getWindowHandle method to get ID of new window (child window)
        Set<String> Child_id = driver.getWindowHandles();

        // for each loop
        for (String a : Child_id) {
            // it will print IDs of both window
            System.out.println(a);

            // condition to change the focus of selenium
            if (Parent_id.equals(a)) {
            }
            else { // to change focus on new window
                driver.switchTo().window(a);
                Thread.sleep(2000);

                // to handle the popup regarding cookies
                driver.findElement(By.xpath("// button")).click();

                // to click on (Read more here)
                je.executeScript("window.scrollBy(0, 600)");
                driver.findElement(By.xpath("(// a)[1]")).click();

                // statement to understand that operation is performed on new window
                System.out.println("operation is performed on new window");
            }
        }
    }
}

Console Output:

Console Output

Output Video

Conclusion

Effectively managing multiple windows in Selenium ensures that your automated tests can interact with all parts of your web application, including new tabs and pop-ups. By utilizing Selenium's built-in capabilities to switch between different windows or tabs, you can create robust and reliable test cases that cover a broader range of user interactions. This approach not only improves the accuracy of your tests but also helps in verifying the complete functionality of your web application in various scenarios



Next Article
Article Tags :
Practice Tags :

Similar Reads