You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Playwright验证已打开2个网页标签页?

如何用Playwright验证已打开2个标签页?

当然可以用.toHaveCount(2)来实现标签页数量的验证,这是最直接的方案。结合页面加载状态等待,还能让验证更稳定。

实现思路

Playwright的浏览器上下文(context)提供了pages()方法,会返回当前上下文所有活跃的页面实例,每个实例对应一个打开的标签页。你只需要在验证新页面URL之后,对context.pages()的数量做断言即可。

修改后的完整代码

test('Click button link test using blank target', async () => {
    const browser = await chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('<my weblink>');
    const newPagePromise = new Promise((resolve) => context.once('page', resolve));

    // Button locator used to click the button to open the link
    const buttonLocator = page.locator('.MuiButton-root');

    // Click the button
    await buttonLocator.click();

    // Wait for the new page to be created
    const newPage = await newPagePromise;
    // 等待新页面完全加载,避免计数时页面还未完全初始化
    await newPage.waitForLoadState();
    
    // Verify that after clicking on the page that the correct URL is present
    expect(newPage.url()).toContain('https://www.google.ca');
    
    // 验证当前打开的标签页数量为2
    expect(context.pages()).toHaveCount(2);

    // 关闭资源,避免泄漏
    await context.close();
    await browser.close();
});

额外说明

  • 加上await newPage.waitForLoadState()是更优的细节:确保新页面的DOM、资源都加载完成后再做断言,避免因页面未完全初始化导致的计数不准确(比如某些场景下新页面已创建但还未完全注册到上下文的情况)。
  • 通常情况下,context.pages()只会统计独立的标签页/窗口,iframe不会被算作单独的page实例,不用担心误统计。

内容的提问来源于stack exchange,提问作者The Olly Bee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:40:51