Multiple Windows & Tabs
Each recipe card on RecipeBox has a "View Full Recipe" link with target="_blank", which opens the full recipe page in a new browser tab rather than navigating away from the list. Selenium's driver object is always focused on exactly one window/tab at a time — clicking that link opens the new tab in the background, but Selenium keeps looking at the tab it was already on until you explicitly tell it to switch.
Window Handles
Every open browser window or tab has a unique identifier string called a window handle.
// The handle of the window/tab Selenium is currently focused on
String originalWindow = driver.getWindowHandle();
// The set of handles for every window/tab currently open
Set<String> allWindows = driver.getWindowHandles();
System.out.println("Currently open windows: " + allWindows.size());
Note: getWindowHandles() returns a
Set<String>, which has no guaranteed order. You can't assume "the new
tab is the last one" by index — instead, loop through the set and skip the handle you already know
about (the original window).
Switching to the New Tab
String originalWindow = driver.getWindowHandle();
driver.findElement(By.linkText("View Full Recipe")).click();
// Loop through all open handles and switch to whichever one isn't the original
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(originalWindow)) {
driver.switchTo().window(handle);
break;
}
}
Full Worked Example: Verify, Then Return
String originalWindow = driver.getWindowHandle();
driver.findElement(By.linkText("View Full Recipe")).click();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(originalWindow)) {
driver.switchTo().window(handle);
break;
}
}
// Now focused on the new tab - verify its content
String heading = driver.findElement(By.tagName("h1")).getText();
System.out.println("New tab heading: " + heading);
// Option A: close the new tab and return to the original
driver.close();
driver.switchTo().window(originalWindow);
// Option B (alternative): just switch back without closing the new tab
// driver.switchTo().window(originalWindow);
Explanation:
- driver.close() closes only the currently focused tab/window — the browser process itself stays alive as long as at least one window remains.
- After closing the new tab, Selenium's focus doesn't automatically snap back to the original — you still must call switchTo().window(originalWindow).
- driver.quit() is different again: it closes every window and ends the whole WebDriver session. Never call it when you only meant to close one tab.
Next: Clicking a link doesn't always mean the new tab has finished loading
yet — see Waits: Implicit, Explicit & Fluent for how to wait
reliably instead of guessing with Thread.sleep().