asked 3 months ago
Switch to the window: Selenium WebDriver can also handle multiple browser windows. When a new window is opened from the current session (for example, by clicking a link), the driver must switch its context to the newly opened window in order to interact with it.
getWindowHandle() - Returns the handle of the current window.
getWindowHandles() - Returns a set of all open window handles.
driver.switchTo().window(handle) - Switches WebDriver's focus to a different window using the window handle.
Example: Switching to a New Window and Back:
Navigate to https://www.qafeast.com/demo, and click the window tab.
Click the hyperlink "Click here" to view the new window
// Store the current window handle
String parentHandle = driver.getWindowHandle();
// Get all window handles
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle); // Switch to new window
}
// Perform actions in the new window
System.out.println("New Window URL: " + driver.getCurrentUrl());
// Close the new window
driver.close();
// Switch back to the parent window
driver.switchTo().window(parentHandle);
System.out.println("Back to Parent Window URL: " + driver.getCurrentUrl());
Close the newly opened window when done
Switch back to the original window