All challenges · Advanced Techniques

Challenge 20 of 29 · Stretch skills · Advanced Techniques

Handle a Popup Window

Some links open a new tab. Listen for the new page before clicking so your test can follow it.

Skills you will practise

  • new pages
  • waitForEvent
  • listener before action

The concept

Links with target="_blank" and calls to window.open() create a new page in the same browser context. Your existing page variable still points at the original tab, so any locator you write keeps searching the old page.

Playwright emits a popup event on the page that opened it (and a page event on the browser context). The pattern is the same as for network waits: start waiting before the action. Create the Promise with page.waitForEvent('popup'), click the link, then await the Promise to get a handle to the new page.

Once you have it, use it like any other page: assert its URL, find elements, close it.

The fragile version

Fragile
await page.getByRole('link', { name: 'Open help' }).click();
await expect(page.getByRole('heading', { name: 'Help centre' })).toBeVisible();

Why it breaks: The heading is in the new tab, but the assertion looks in the original one, so it times out.

A robust Playwright version

Robust
const popupPromise = page.waitForEvent('popup');
await page.getByRole('link', { name: 'Open help' }).click();
const popup = await popupPromise;
await popup.waitForLoadState();
await expect(popup.getByRole('heading', { name: 'Help centre' })).toBeVisible();

It listens first, captures the new page, and asserts in the right tab.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Waiting for the popup after clicking.
  • Continuing to use the original page variable for the new tab.
  • Not handling the case where the app opens the link in the same tab on small screens.

FAQ

How do I get a new tab in Playwright?

const p = page.waitForEvent('popup'); await click; const popup = await p;

What is the difference between popup and context page events?

popup fires on the opener page; the context page event fires for any new page in the context.

How do I switch back to the first tab?

Keep using the original page variable; it still points at that tab.

Try it

Practise this in Challenge 20. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.

Practise this challenge free