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

Playwright测试报错‘Target page, context or browser has been closed’求助

问题描述

一段Playwright登录页面测试代码数月前可正常运行,现在执行时触发错误:page.title: Target page, context or browser has been closed,错误出现在点击登录链接后获取页面标题的步骤。即使将代码移至注释中提及的封装函数内,问题仍存在。

测试代码:

test("@Login @Testing Sign In Page Test", async ({ page }) => {
    console.log("Sign In Page Test");

    const pageManager = new pageObjectManager(page);
    const homePage = pageManager.getHomePage();
    const loginPage = pageManager.getLoginPage();
    const signInPage = pageManager.getSignInPage();

    // await homePage.goToHomePage();
    await page.goto("https://magento.softwaretestingboard.com/");

    // await loginPage.goToSignInPage();
    console.log(await page.title());
    await page.locator("//li[@class='authorization-link']").first().click();

    // await signInPage.validateLandingOnSignInPage();
    console.log(await page.title());
    await expect(page).toHaveTitle("Customer Login");
});

报错信息:

Error: page.title: Target page, context or browser has been closed

      34 |
      35 |      // await signInPage.validateLandingOnSignInPage();
    > 36 |      console.log(await page.title());
         |                             ^
      37 |      await expect(page).toHaveTitle("Customer Login");
      38 | });
      39 |
排查思路与解决方案
  • 页面跳转导致原page对象失效:点击登录链接后,可能目标页面在新标签页打开,或者原页面导航过程中出现异常,导致原page对象被标记为已关闭。可以通过监听页面事件来处理:

    // 情况1:点击后打开新标签页
    const signInPagePromise = page.waitForEvent('popup');
    await page.locator("//li[@class='authorization-link']").first().click();
    const signInPage = await signInPagePromise;
    console.log(await signInPage.title());
    await expect(signInPage).toHaveTitle("Customer Login");
    
    // 情况2:原页面跳转
    const navigationPromise = page.waitForNavigation({ waitUntil: 'networkidle' });
    await page.locator("//li[@class='authorization-link']").first().click();
    await navigationPromise;
    console.log(await page.title());
    
  • Playwright版本兼容性问题:数月前的代码现在报错,大概率是框架版本更新后行为或API发生变化。可以尝试回退到之前可用的版本,或者升级到最新稳定版,同时检查是否使用了已废弃的API。

  • 页面加载未完成就执行操作:网站可能更新了前端逻辑,导致点击登录后页面还没加载完成,就调用了page.title()。可以添加等待关键元素的步骤:

    await page.locator("//li[@class='authorization-link']").first().click();
    // 等待登录页面的邮箱输入框加载完成
    await page.waitForLocator("#email", { timeout: 10000 });
    console.log(await page.title());
    
  • 上下文/浏览器意外关闭:检查测试框架的配置,是否存在自动关闭上下文的逻辑,或者测试执行中浏览器进程被意外终止。可以添加日志排查页面状态:

    console.log("点击前页面是否关闭:", page.isClosed());
    await page.locator("//li[@class='authorization-link']").first().click();
    console.log("点击后页面是否关闭:", page.isClosed());
    

内容的提问来源于stack exchange,提问作者Satya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:29:54