Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(page): make page.title() return empty string instead of throwing during navigation (#39658)

Yury Semikhatskya92363b68055
diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts
index a09b41d050..3f7f2cc5fd 100644
--- a/packages/playwright-core/src/server/frames.ts
+++ b/packages/playwright-core/src/server/frames.ts
@@ -1566,8 +1566,17 @@ export class Frame extends SdkObject<FrameEventMap> {
}
async title(): Promise<string> {
- const context = await this._utilityContext();
- return context.evaluate(() => document.title);
+ try {
+ return await this.raceAgainstEvaluationStallingEvents(async () => {
+ const context = await this._utilityContext();
+ return await context.evaluate(() => document.title);
+ });
+ } catch {
+ const url = this.pendingDocument()?.request?.url();
+ if (url)
+ return `Loading ${url}`;
+ return '';
+ }
}
async rafrafTimeout(progress: Progress, timeout: number): Promise<void> {
diff --git a/packages/playwright-core/src/tools/dashboard/dashboardController.ts b/packages/playwright-core/src/tools/dashboard/dashboardController.ts
index aae1285422..fd8bb68e1f 100644
--- a/packages/playwright-core/src/tools/dashboard/dashboardController.ts
+++ b/packages/playwright-core/src/tools/dashboard/dashboardController.ts
@@ -244,8 +244,7 @@ export class DashboardConnection implements Transport, DashboardChannel {
return [];
const devtoolsUrl = await this._devtoolsUrl(pages[0]);
return await Promise.all(pages.map(async page => {
- // page.title() throws on navigation.
- const title = await page.title().catch(() => undefined) || `Loading ${page.url()}`;
+ const title = await page.title();
return {
pageId: this._pageId(page),
title,
diff --git a/tests/page/page-basic.spec.ts b/tests/page/page-basic.spec.ts
index e8d9bc5a8e..cf923d747a 100644
--- a/tests/page/page-basic.spec.ts
+++ b/tests/page/page-basic.spec.ts
@@ -85,6 +85,18 @@ it('page.title should return the page title', async ({ page, server }) => {
expect(await page.title()).toBe('Woof-Woof');
});
+it('page.title should not throw during navigation', async ({ page, server }) => {
+ await page.setContent('<title>hello</title>');
+ const promise = page.goto(server.PREFIX + '/title.html');
+ const [titleOrError] = await Promise.all([
+ page.title().catch(e => e),
+ promise,
+ ]);
+ expect(typeof titleOrError).toBe('string');
+ expect(titleOrError).toMatch(/^(Loading http.*title.html|hello|Woof-Woof)$/);
+ await expect(page).toHaveTitle('Woof-Woof');
+});
+
it('page.close should work with window.close', async function({ page }) {
const newPagePromise = page.waitForEvent('popup');
await page.evaluate(() => window['newPage'] = window.open('about:blank'));