Wednesday, July 3, 2024
HomeLanguagesJavaHow to Handle Multiple Windows in Selenium using Java?

How to Handle Multiple Windows in Selenium using Java?

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 required ChromeDriver you can download it from the official site of selenium. We will use the neveropen.co.za website for automation practice.

Steps

  1. Visit the official site of neveropen.co.za
  2. Click on courses at Lazyroar 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.neveropen.co.za/");
 
        // 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 Lazyroar'])[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 clicked 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 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.neveropen.co.za/");
 
        // 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 Lazyroar'])[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.neveropen.co.za/");
 
        // 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 Lazyroar'])[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 

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments