Open In App

How to handle multiple windows in Selenium?

Last Updated : 16 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes when we click on a particular web element it opens a new window. To locate the web elements on the new window webpage, we need to shift the focus of selenium from the current page (main page) to the new page. In this article, we will try to shift the focus of selenium from one window to another new window. Here we will use the Chrome browser for which we require ChromeDriver you can download it from the official site of Selenium. We will use the geeksforgeeks.org website for automaChromeon practice.

Steps:

  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[text()='Courses at GeeksforGeeks'])[2]")).click();
  
        // to select a particular course
        Thread.sleep(2000);
        driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[1]")).click();
  
        // it will open with new tab
  
        // to click on (Read more here) on new window
        driver.findElement(By.xpath("(// a[text()='(Read more here)'])[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

 

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[text()='Courses at GeeksforGeeks'])[2]")).click();
  
        // to select a particular course
        Thread.sleep(2000);
        driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[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[text()='Courses at GeeksforGeeks'])[2]")).click();
  
        // to select a particular course
        Thread.sleep(2000);
        driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[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[text()='Got it!']")).click();
  
                // to click on (Read more here)
                je.executeScript("window.scrollBy(0, 600)");
                driver.findElement(By.xpath("(// a[text()='(Read more here)'])[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 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads