0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Get Window Handle in Selenium: Syntax and Example

In Selenium, you can get the current window handle using driver.getWindowHandle(). This returns a unique string ID for the browser window, which helps when switching between multiple windows or tabs.
๐Ÿ“

Syntax

The method getWindowHandle() is called on the WebDriver instance to get the current window's unique handle as a string.

  • driver: Your WebDriver object controlling the browser.
  • getWindowHandle(): Returns the window handle as a string.
java
String windowHandle = driver.getWindowHandle();
๐Ÿ’ป

Example

This example shows how to open a browser, navigate to a page, get the current window handle, and print it.

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

public class WindowHandleExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        String windowHandle = driver.getWindowHandle();
        System.out.println("Current window handle: " + windowHandle);

        driver.quit();
    }
}
Output
Current window handle: CDwindow-1234ABCD5678EFGH
โš ๏ธ

Common Pitfalls

Common mistakes when using getWindowHandle() include:

  • Confusing getWindowHandle() (single window) with getWindowHandles() (all open windows).
  • Not storing the handle before opening new windows, making it hard to switch back.
  • Using the handle string incorrectly when switching windows.
java
/* Wrong way: Trying to switch using a wrong handle string */
driver.switchTo().window("wrong-handle"); // Throws NoSuchWindowException

/* Right way: Store handle first, then switch */
String originalHandle = driver.getWindowHandle();
// open new window
// switch back
driver.switchTo().window(originalHandle);
๐Ÿ“Š

Quick Reference

MethodDescription
getWindowHandle()Returns the current window handle as a String
getWindowHandles()Returns a Set of all open window handles
switchTo().window(handle)Switches focus to the window with the given handle
โœ…

Key Takeaways

Use driver.getWindowHandle() to get the current browser window's unique ID.
Store window handles before opening new windows to switch back easily.
Do not confuse getWindowHandle() with getWindowHandles(), which returns all windows.
Use the window handle string with driver.switchTo().window(handle) to change focus.
Always quit the driver to close browser windows after tests.