Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to use close() and quit() method in Selenium Python ?
Next article icon

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[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
output

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath", "selector":"(//a[text 1="more" 2="here)'" language="()='(Read"][/text])[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

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
How to use close() and quit() method in Selenium Python ?
author
badesuraj9
Improve
Article Tags :
  • Java
  • Software Testing
Practice Tags :
  • Java

Similar Reads

  • How to Handle iframe in Selenium with Java?
    In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed. Table of Content What are iframes in Selenium?Difference between frame and iframe in SeleniumSteps to Identify a Frame on a Page?How to Switch Over the Elements in ifram
    11 min read
  • How to Handle Alert in Selenium using Java?
    Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated
    6 min read
  • How to handle alert prompts in Selenium Python ?
    Selenium’s Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. Selenium’s Python Module is built to perform automated testing with Python
    2 min read
  • How to Scroll an Element into View in Selenium?
    A high-level programming language that helps users in building web applications is called Java. It is not only used for creating web applications but it can also be used for automating web applications through various automation tools. Selenium is one such tool, which gives users the capability to a
    4 min read
  • How to use close() and quit() method in Selenium Python ?
    While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the drive
    2 min read
  • How to handle Frames/iFrames in Selenium with Python
    Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate yo
    2 min read
  • How to scrape multiple pages using Selenium in Python?
    As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are g
    4 min read
  • How to save and load cookies in Selenium using Python
    In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Pyth
    4 min read
  • minimize_window driver method - Selenium Python
    Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just bein
    2 min read
  • set_window_position driver method - Selenium Python
    Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just bein
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences