参考: https://www.programsbuzz.com/article/how-handle-multiple-tabs-playwright

例如这样的:

test.only('verify multiple tabs', async({context})=>{
const page = await context.newPage();
await page.goto("https://www.programsbuzz.com/")
const [newPage] = await Promise.all([
context.waitForEvent('page'),
// This action triggers the new tab
page.locator('text=By iVagus Services Pvt. Ltd.').click() 
])
// title of new tab page
console.log(await newPage.title());
// title of existing page
console.log(await page.title());
})

那么获得京东的首页,进入首页的秒杀页面,进入商品的详情页面就是这样的:

const { test, expect } = require('@playwright/test');
test.only('verify multiple tabs', async({context})=>{
  const page = await context.newPage();
  await page.goto('https://www.jd.com/?d')
  await page.waitForTimeout(5000);
  const [newPage] = await Promise.all([
    context.waitForEvent('page'),
    // This action triggers the new tab
    //page.getByText('(全8册,少年读史记,国学早启蒙。100余位历史人物传记,图文并茂,提高作文水平)').last().click();
    //page.waitForTimeout(5000);
    page.locator('text=史记少年版').first().click()
  ])
  const [showPage] = await Promise.all([
    context.waitForEvent('page'),
    // This action triggers the new tab
    //page.getByText('(全8册,少年读史记,国学早启蒙。100余位历史人物传记,图文并茂,提高作文水平)').last().click();
    //page.waitForTimeout(5000);
    page.locator('text=史记少年版').first().click()
  ])
  console.log(await showPage.title());
  console.log(await showPage.url());
  // title of new tab page
  console.log(await newPage.title());
  console.log(await newPage.url());
  // title of existing page
  console.log(await page.title());
  console.log(await page.url());
})

运行后,通过了:npx playwright test jing.spec.js --debug

Running 2 tests using 1 worker
[firefox] › jing.spec.js:3:6 › verify multiple tabs
京东秒杀-正品保证、天天低价、限时限量
https://miaosha.jd.com/#13119711
京东秒杀-正品保证、天天低价、限时限量
https://miaosha.jd.com/#13119711
京东(JD.COM)-正品低价、品质保障、配送及时、轻松购物!
https://www.jd.com/?d
[webkit] › jing.spec.js:3:6 › verify multiple tabs
京东秒杀-正品保证、天天低价、限时限量
https://miaosha.jd.com/#13119711
京东秒杀-正品保证、天天低价、限时限量
https://miaosha.jd.com/#13119711
京东(JD.COM)-正品低价、品质保障、配送及时、轻松购物!
https://www.jd.com/?d
  2 passed (39s)
To open last HTML report run:
  npx playwright show-report