Selenium

Handle Multiple Tabs and Windows in Selenium 4 – getWindowHandle & getWindowHandles Tutorial

Handle Multiple Tabs and Windows in Selenium 4 – Complete Practical Guide

By Bhau Automation • Selenium 4 Window Handling Tutorial

🎯 What You Will Learn in This Video

  • How to open new tabs and windows in Selenium 4
  • Difference between getWindowHandle and getWindowHandles
  • How to switch between multiple browser windows
  • Practical examples using Selenium WebDriver
  • Handling multiple tabs in automation frameworks
💡 Practice Selenium automation using our demo site: https://www.bhauautomation.com/ → Go to Services → Selenium Automation Practice Page.

📌 What is Window Handling in Selenium?

In Selenium WebDriver, sometimes clicking a link opens a new browser tab or window. To interact with that new window, Selenium provides two important methods:

  • getWindowHandle()
  • getWindowHandles()

🔹 getWindowHandle()

This method returns the unique ID of the current browser window.

String parentWindow = driver.getWindowHandle();
System.out.println(parentWindow);

🔹 getWindowHandles()

This method returns the IDs of all open browser windows as a Set.

Set allWindows = driver.getWindowHandles();

for(String window : allWindows){
    driver.switchTo().window(window);
}

💻 Complete Selenium Example

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

public class MultipleWindowsExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();
driver.get("https://www.bhauautomation.com");

String parent = driver.getWindowHandle();

Set windows = driver.getWindowHandles();

for(String window : windows){

if(!window.equals(parent)){

driver.switchTo().window(window);
System.out.println("Switched to child window");

}

}

driver.quit();

}

}

🔄 Steps to Handle Multiple Windows

  • Get parent window ID
  • Click link that opens new window
  • Use getWindowHandles() to get all windows
  • Loop through windows
  • Switch using driver.switchTo().window()

🎯 Real-World Use Cases

  • Handling payment gateway windows
  • Social media login popups
  • Multiple tab navigation
  • External links opening new browser tabs

❓ Interview Questions

Q: What is the difference between getWindowHandle and getWindowHandles?

A: getWindowHandle returns the ID of the current window while getWindowHandles returns IDs of all open windows.

Q: How do you switch between windows in Selenium?

A: Using driver.switchTo().window(windowID)

🎥 Watch the Complete Tutorial

👉 Watch on YouTube: Handle Multiple Tabs and Windows in Selenium 4

🎓 Key Takeaways

  • Use getWindowHandle() to identify current window
  • Use getWindowHandles() to get all windows
  • Switch windows using driver.switchTo().window()
  • Essential concept for Selenium automation frameworks
  • Frequently asked Selenium interview question

🚀 Created with ❤️ by Bhau Automation

Back to All Articles