New tabs and pop-up windows
IntermediateA link that opens a new tab and a button that opens a small pop-up window.
Practice area
Tasks to automate
- Click the link, switch to the new tab, assert its heading, close it and return to the first tab.
- Open the pop-up window, read its URL and title, close it.
- Assert that exactly one window is open at the start and after you have closed the others.
Model solutions
Try the tasks first. These show one good way, not the only way.
Selenium (Java)
String original = driver.getWindowHandle();
driver.findElement(By.id("pg-new-tab")).click();
new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(original)) driver.switchTo().window(handle);
}
assertEquals("Child window", driver.findElement(By.tagName("h1")).getText());
driver.close(); // closes the child only
driver.switchTo().window(original); // you must switch back yourself
Playwright (TypeScript)
const [child] = await Promise.all([
page.waitForEvent('popup'),
page.locator('#pg-new-tab').click(),
]);
await child.waitForLoadState();
await expect(child.locator('h1')).toHaveText('Child window');
await child.close();
await expect(page.locator('#pg-new-tab')).toBeVisible(); // original page is still usable
Element IDs on this page are stable and will not change. Nothing you do here is sent to a server.
