How can I check if a new browser tab was opened?

Viewed 1588

In a web application (implemented in React), when I press a specific button, then a new browser tab is opened. I would like to check that this happened and if the URL of the new tab is correct.

1 Answers

You could implement it like that

// @ts-check
const playwright = require("playwright");

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.org/');

  // Important to "start" this promise before the window.open() could happen
  const newPagePromise = new Promise(resolve => context.once("page", resolve))

  // Imagine some internal window.open() logic
  await page.evaluate(() => {
    setTimeout(() => {
      window.open("https://github.com/microsoft/playwright", "_blank")
    }, 3 * 1000)
  })

  // Here we are waiting until the page has been opened
  const newPage = await newPagePromise

  // Since its a normal Page instance, we can now assert the URL of it
  console.log(newPage.url(), await newPage.title())

  await browser.close();
})();

See it here interactively on Try Playwright: https://try.playwright.tech/?s=g8vb1si

Related