Test Automation Blog

Tools, Tips and Thoughts for Playwright, Selenium UI and API automated testing

Handling new browser tabs in Playwright

Sometimes performing an action opens up a web page in a new browser tab, so how can we handle this in Playwright? TL;DR: with a new Page object.

You can see an example of a new browser tab being opened on the Playwright GitHub page in the link to the Playwright developer community website.

You might at first try a Playwright automated test that looks something like the following code:

test('GitHub Playwright link opens in new tab', async ({page}) => {
  await page.goto('https://www.github.com/microsoft/playwright');
  await page.getByRole('link', { name: 'playwright.dev' }).click();
  await expect(page.getByRole('link', { name: 'Get Started'})).toBeVisible();
});

However you will find it does not work because the elements are on a new page, so instead you will need to create a new page object, like so:

test('GitHub Playwright link opens in new tab', async ({page, context}) => {
  await page.goto('https://www.github.com/microsoft/playwright');
  const pagePromise = context.waitForEvent('page');
  await page.getByRole('link', { name: 'playwright.dev' }).click();
  const newPage = await pagePromise;
  await expect(newPage.getByRole('link', { name: 'Get Started'})).toBeVisible();
});

Note the code in bold, in particular the waitForEvent which is called before the action that opens the page in the new tab, and also the await statement which retrieves a new page instance after the link is clicked. Also note the requirement to pass the Playwright context variable parameter.

Handling new browser tabs in Playwright
Scroll to top