From 416e7ac6918814981a35b63bd2151be653993a59 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo Date: Wed, 25 Nov 2026 13:09:56 +0100 Subject: [PATCH 1/4] feat(web): add browser.consoleMessages() and browser.pageErrors() --- .changeset/browser-console-messages.md | 5 + .fallowrc.json | 1 + apps/testbed/tests/browser.e2e.ts | 23 +++ .../tests/newsletter-signup.e2e.ts | 34 +--- docs/migrate/cypress.mdx | 2 +- docs/migrate/playwright.mdx | 3 +- docs/migrate/selenium.mdx | 3 +- docs/reference/web.mdx | 112 +++++++++++- packages/web/src/attempt-session.ts | 7 +- packages/web/src/browser.ts | 43 +++++ packages/web/src/engine-entry.ts | 2 + packages/web/tests/helpers/fixture-app.ts | 42 +++++ .../integration/console-messages.test.ts | 172 ++++++++++++++++++ packages/web/tests/types/console-messages.ts | 22 +++ .../web/tests/unit/attempt-session.test.ts | 2 + .../skills/e2e/references/writing-tests.md | 7 + skills/e2e/references/writing-tests.md | 7 + 17 files changed, 453 insertions(+), 34 deletions(-) create mode 100644 .changeset/browser-console-messages.md create mode 100644 packages/web/tests/integration/console-messages.test.ts create mode 100644 packages/web/tests/types/console-messages.ts diff --git a/.changeset/browser-console-messages.md b/.changeset/browser-console-messages.md new file mode 100644 index 0000000000..77c1a189c4 --- /dev/null +++ b/.changeset/browser-console-messages.md @@ -0,0 +1,5 @@ +--- +'@e2e-dev/web': patch +--- + +Add `browser.consoleMessages()` and `browser.pageErrors()` to return the active tab's console messages and uncaught errors. diff --git a/.fallowrc.json b/.fallowrc.json index e51e63070e..c02d3f58b7 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -29,6 +29,7 @@ "packages/web/tests/types/downloads.ts", "packages/web/tests/types/app.ts", "packages/web/tests/types/engine.ts", + "packages/web/tests/types/console-messages.ts", "packages/mobile/tests/types/options.ts", "packages/mobile/tests/types/engine.ts", "packages/desktop/tests/types/engine.ts", diff --git a/apps/testbed/tests/browser.e2e.ts b/apps/testbed/tests/browser.e2e.ts index fa30896220..44dc08a448 100644 --- a/apps/testbed/tests/browser.e2e.ts +++ b/apps/testbed/tests/browser.e2e.ts @@ -50,6 +50,29 @@ test.describe('browser fixture', { platforms: ['web'], tags: ['browser'] }, () = const theme = (await browser.cookies()).find((cookie) => cookie.name === 'theme'); expect(theme?.value).toBe('dark'); }); + + test('console messages and page errors read back and clear on restart', async ({ app, browser }) => { + // FIXME: headed Chromium and hosted Chrome request /favicon.ico and log a + // 404 because the playground doesn't serve it. A headless run doesn't, so + // the message is left out to keep the lists the same in every mode. + const logged = async () => (await browser.consoleMessages()).filter((message) => !message.text.startsWith('Failed to load resource')); + + await browser.evaluate(() => { + console.error('broken', 42); + void Promise.reject(new Error('rejected')); + setTimeout(() => { + throw new Error('thrown'); + }); + return null; + }); + await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message).toSorted()).toEqual(['rejected', 'thrown']); + expect(await logged()).toEqual([{ type: 'error', text: 'broken 42' }]); + + await app.restart(); + + expect(await logged()).toEqual([]); + expect(await browser.pageErrors()).toEqual([]); + }); }); test('offline fails the page\'s requests and navigations until the test goes back online', { platforms: ['web'], tags: ['browser'] }, async ({ app, screen, browser }) => { diff --git a/apps/web-benchmark/tests/newsletter-signup.e2e.ts b/apps/web-benchmark/tests/newsletter-signup.e2e.ts index fccaf568c0..bd5bf62e20 100644 --- a/apps/web-benchmark/tests/newsletter-signup.e2e.ts +++ b/apps/web-benchmark/tests/newsletter-signup.e2e.ts @@ -1,31 +1,8 @@ import { test } from '@e2e-dev/web'; -import type { Browser } from '@e2e-dev/web'; import { expect } from 'e2e'; -type ConsoleErrorStore = Window & { e2eConsoleErrors?: string[] }; - -/** - * Hooks `console.error` in the page and returns a reader of what the app has - * logged since. The planted bug's only trace is a console error, and the - * engine has no `browser.onConsole` yet, so the page keeps the list itself. - */ -async function captureConsoleErrors(browser: Browser): Promise<() => Promise> { - await browser.evaluate(() => { - const errors: string[] = []; - (window as ConsoleErrorStore).e2eConsoleErrors = errors; - const original = console.error; - console.error = (...args: unknown[]) => { - errors.push(args.map(String).join(' ')); - original(...args); - }; - return null; - }); - return () => browser.evaluate(() => (window as ConsoleErrorStore).e2eConsoleErrors ?? []); -} - test('subscribe renders no feedback and logs a TypeError (planted bug)', async ({ app, screen, browser }) => { await app.open('/e/newsletter-signup'); - const consoleErrors = await captureConsoleErrors(browser); const email = screen.getByPlaceholder('you@example.com'); await email.fill('maria.novak@example.com'); await screen.getByRole('button', 'Subscribe').tap(); @@ -33,7 +10,12 @@ test('subscribe renders no feedback and logs a TypeError (planted bug)', async ( await expect(screen.getByTestId('success-message')).not.toBeVisible(); await expect(screen.getByTestId('error-message')).not.toBeVisible(); await expect(email).toHaveValue('maria.novak@example.com'); - await expect.poll(async () => (await consoleErrors()).join('\n')).toContain( - "Cannot read properties of undefined (reading 'subscribe')", - ); + await expect.poll(async () => { + const messages = await browser.consoleMessages(); + + return messages + .filter((message) => message.type === 'error') + .map((message) => message.text) + .join('\n'); + }).toContain("Cannot read properties of undefined (reading 'subscribe')"); }); diff --git a/docs/migrate/cypress.mdx b/docs/migrate/cypress.mdx index 6f2268462e..d044630961 100644 --- a/docs/migrate/cypress.mdx +++ b/docs/migrate/cypress.mdx @@ -125,7 +125,7 @@ Planned gaps are on the roadmap, and Not yet gaps have no date. Not planned gaps | `.trigger()`, `cy.scrollTo()` | `hover()`, `dragTo()`, `scrollIntoView()`; for other synthetic events use `browser.evaluate` | | `cy.intercept({ headers })` and other header matchers | Check `route.request.headers` in the handler, else call `route.fallback()` | | `cy.wait('@alias')`, `.its('request.body')`, `@alias.all` | Start `browser.waitForResponse(pattern)` before the action; read the request in a `browser.route` handler | -| `Cypress.on('uncaught:exception')` | An app error doesn't fail a test. To fail on one, collect `window.onerror` in `browser.addInitScript`, then assert the list is empty with `browser.evaluate` | +| `Cypress.on('uncaught:exception')` | An app error doesn't fail a test. To fail on one, assert that [`browser.pageErrors()`](/reference/web#pageerrors) is empty | | `--browser chrome`, `edge`, `electron`, `before:browser:launch` | `web({ browser: 'chromium' })`, or attach to your own Chrome with `web({ connect: { cdpEndpoint } })` | | `cypress open`, time-travel snapshots | `npx e2e run --headed --watch`, or `--step`; the [trace page](/debugging#traces) shows each step after the run | | `before()` and `after()` that drive the app, `describe.only` | UI setup in `beforeEach`, cleanup in `afterEach`; sign-in in a top-level `test.setup` that saves a session; `test.only` on each test | diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index 75cc3fc605..a46e8a81ad 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -171,6 +171,7 @@ run only in a browser, so a test that uses it declares | `context.pages()`, `context.newPage()`, `page.bringToFront()` | `browser.tabs()`, `browser.newTab()`, `tab.activate()`; no `context.on('page')` event | | `page.evaluate(fn, arg)` | `browser.evaluate(fn, arg)`, JSON in and out | | `page.webmcp.tools()`, `page.webmcp.callTool(name, input)` | the same on `browser.webmcp`, with `web({ webmcp: true })` in place of the launch argument or preferences; the main frame only, see [WebMCP](/reference/web#webmcp) | +| `page.consoleMessages()`, `page.pageErrors()`, `page.on('console')`, `page.on('pageerror')` | Read [`browser.consoleMessages()`](/reference/web#consolemessages) or [`browser.pageErrors()`](/reference/web#pageerrors) after the action. Both return everything since the tab opened, like Playwright's `{ filter: 'all' }`. There are no console or page error listeners | | `page.addInitScript()`, `page.emulateMedia({ colorScheme, reducedMotion })` | `browser.addInitScript()` or `web({ initScripts })`; `browser.emulateMedia()` | | `context.addCookies()`, `cookies()`, `clearCookies()` | `browser.setCookies()`, `browser.cookies()`, `browser.clearCookies()` | | `context.setOffline(true)` | [`browser.setNetwork('offline')`](/reference/web#setnetwork), `'online'` to go back | @@ -293,7 +294,7 @@ purpose. Use the workaround, or keep the test in Playwright. | `waitForResponse(predicate)`, `waitForRequest()`, `page.on('request')`, `response.ok()` | `browser.waitForResponse(pattern)`, or `{ method, url }` to filter on the request's method, then check the response in the test, `status` for `ok()`. For requests, a `browser.route` handler that records `route.request`, then calls `route.fallback()` | | `route.fulfill({ response })`, `route.abort(code)`, `route.fetch(options)`, `request.postDataJSON()` | `status`, `headers`, and `body` from `route.fetch()`; `JSON.parse(route.request.postData)` | | `page.addLocatorHandler()` | Dismiss the overlay in `beforeEach`, or set its consent cookie with `browser.setCookies` | -| `page.on('console')`, `page.on('pageerror')`, `page.clock` | A `browser.addInitScript` that records to a `window` array, or that stubs `Date` | +| `page.clock` | A `browser.addInitScript` that stubs `Date` | | `setGeolocation()`, `grantPermissions()` | A `browser.addInitScript` stub; `app.permissions` on the target | | `ignoreHTTPSErrors`, `proxy`, `channel`, `launchOptions` | Serve the app over `http`; start the browser yourself and attach with `web({ connect })` | diff --git a/docs/migrate/selenium.mdx b/docs/migrate/selenium.mdx index 557622ee27..31ebcd1f23 100644 --- a/docs/migrate/selenium.mdx +++ b/docs/migrate/selenium.mdx @@ -94,6 +94,7 @@ test('signs in', async ({ app, screen, browser }) => { | `switchTo().frame()`, `switchTo().alert().accept()` | `browser.frameLocator('#frame')`, `browser.onDialog('accept')` before the action | | `switchTo().window(handle)`, `getWindowHandles()`, `switchTo().newWindow()` | `tab.activate()`, `browser.tabs()`, `browser.newTab()`; `browser.waitForPopup(() => trigger)` for a tab the app opens, see [Tabs](/reference/web#tabs) | | `executeScript(script, args)` | `browser.evaluate(fn, arg)`, JSON in and out only | +| `manage().logs().get('browser')` | Read console output with [`browser.consoleMessages()`](/reference/web#consolemessages) and uncaught exceptions with [`browser.pageErrors()`](/reference/web#pageerrors). Reading a list doesn't clear it | | Page objects | A fixture from `test.extend`, or a goal for `agent.act`, see [Page objects](/page-object-model) | ## What e2e doesn't have yet @@ -110,7 +111,7 @@ e2e leaves it out on purpose. | `ChromeOptions.addArguments`, `setBinary`, `Proxy`, `acceptInsecureCerts` | Start Chrome or Edge with the flags, then attach with `web({ connect })` | | `@BeforeSuite`, `@AfterSuite`, pytest session-scoped fixtures, WebdriverIO `onPrepare` | Once for the run: the script `app.command` starts, or a wrapper around `e2e run`. Once for a file: `beforeAll` and `afterAll`. Sign-in: a top-level `test.setup` that saves a session | | BrowserStack or Sauce Labs for web | Your own [browser provider](/browser#write-a-provider), if the vendor has a CDP endpoint | -| `manage().logs()`, request listeners, geolocation | Patch the page in `browser.addInitScript`, record requests in `browser.route` | +| Request listeners, geolocation | Record requests in `browser.route`, stub geolocation in `browser.addInitScript` | | `setNetworkConditions` | For offline, [`browser.setNetwork('offline')`](/reference/web#setnetwork). No throttling or latency, keep those tests in Selenium | ### Not yet diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index 101af054b1..fb7faa260f 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -267,6 +267,9 @@ What survives: read current geometry and focus with `browser.evaluate` before acting. - Code that uses `surfaceOf(engine)` must read its accessors again after recovery. Playwright objects it kept belong to the disconnected transport. +- The `browser.consoleMessages()` and `browser.pageErrors()` lists only + keep entries from the current document. Chrome doesn't send the earlier + ones again. A `browser` provider with `scope: 'attempt'` rides the same persistent context, with the same limits. The lease's `cdpEndpoint` provisions the @@ -481,8 +484,9 @@ export type WebInitScript = string | { readonly path: string } | (() => unknown) - What reads or acts on a page acts on the active tab: `goto`, `reload`, `back`, `forward`, `url`, `title`, `waitForURL`, `locator`, `frameLocator`, - `evaluate`, `waitForResponse`, `waitForDownload`, `keyboard`, `mouse`, the - `expect(browser)` matchers, and every `screen` query. + `evaluate`, `consoleMessages`, `pageErrors`, `waitForResponse`, + `waitForDownload`, `keyboard`, `mouse`, the `expect(browser)` matchers, and + every `screen` query. - What belongs to the browser covers every tab: `cookies`, `setCookies`, `clearCookies`, `route`, `unroute`, `unrouteAll`, `onDialog`, and `addInitScript`. @@ -515,6 +519,8 @@ export type WebInitScript = string | { readonly path: string } | (() => unknown) | [`locator`](#locator) | `Locator` | | [`frameLocator`](#framelocator) | `FrameScreen` | | [`evaluate`](#evaluate) | `Promise` | +| [`consoleMessages`](#consolemessages) | `Promise` | +| [`pageErrors`](#pageerrors) | `Promise` | | [`addInitScript`](#init-scripts) | `Promise` | | [`route`](#route) | `Promise` | | [`unroute`](#unroute) | `Promise` | @@ -546,7 +552,7 @@ The [config](/reference/config) sets each member's budget: A `{ timeout }` option overrides the budget on `goto`, `reload`, `back`, `forward`, `waitForResponse`, `waitForPopup`, `waitForDownload`, and `waitForDownloads`, capped -by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `addInitScript`, `route`, +by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `consoleMessages`, `pageErrors`, `addInitScript`, `route`, `unroute`, `unrouteAll`, `cookies`, `setCookies`, `clearCookies`, `setViewport`, `emulateMedia`, `setNetwork`, `onDialog`, `newTab`, the `BrowserTab` methods, `keyboard.*`, `mouse.*`, and `webmcp.*` take no override. @@ -707,6 +713,99 @@ const title = await browser.evaluate('document.title'); | `ACTION_FAILED` | A Playwright timeout. | | `ENGINE_FAILURE` | The page closed or the context was lost. | +#### `consoleMessages` + +Returns the console messages logged in the active tab since it opened, +oldest first. Only the latest 200 are kept. + +```ts +await app.open('/checkout'); +await screen.getByRole('button', 'Place order').tap(); +await expect(screen.getByText('Order placed')).toBeVisible(); +const errors = (await browser.consoleMessages()).filter((message) => message.type === 'error'); +expect(errors).toEqual([]); +``` + +```ts +export interface WebConsoleMessage { + /** + * The message type, such as `'log'`, `'error'`, or `'warning'` (the type of + * `console.warn`). Most values are Playwright's console message types. The + * rest come from one browser: `'verbose'` from Chromium's own messages, + * `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox, and + * `'image'` and `''` from WebKit. + */ + readonly type: + | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose' + | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'image' + | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' + | 'profile' | 'profileEnd' | 'count' | 'countReset' + | 'time' | 'timeLog' | 'timeEnd' | 'timeStamp' | ''; + /** The message text. */ + readonly text: string; +} +``` + +- Messages from the tab's frames and dedicated workers are included. + Messages from service workers aren't. +- The list also has messages the browser writes, such as Chromium's + `Failed to load resource` for a request that got a 404. Headed Chromium + and hosted Chrome request `/favicon.ico` and log a 404 when the app + doesn't have a favicon, while headless runs don't. +- The list isn't cleared on navigation, so messages from earlier documents + in the tab stay in it. +- After `app.restart()`, the list only has messages from the new page. +- Each tab has a separate list. To read another tab's list, activate it. +- A message can show up in the list shortly after it's logged. To wait for + one, use [`expect.poll`](/reference/expect#polling-a-value). As in the + example, wait for the result on screen before asserting the list is empty. + + +On a [persistent context](#recovering-a-cdp-transport), the first tab is +reused. Its `consoleMessages` and `pageErrors` entries from before the +attempt are dropped. Entries from the attempt's init scripts are kept. After +the CDP transport reconnects, the lists only have entries from the current +document. + + +| Throws | When | +| --- | --- | +| `APP_NOT_OPEN` | No page is open yet. | +| `ACTION_FAILED` | The call ran past [`actionTimeout`](/reference/config#actiontimeout). | +| `ENGINE_FAILURE` | The browser connection was lost. | + +#### `pageErrors` + +Returns the uncaught errors and unhandled promise rejections in the active +tab since it opened, oldest first. Only the latest 200 are kept. + +```ts +await app.open('/checkout'); +await screen.getByRole('button', 'Place order').tap(); +await expect(screen.getByText('Order placed')).toBeVisible(); +expect(await browser.pageErrors()).toEqual([]); +``` + +```ts +export interface WebPageError { + /** The error message, as the browser reports it. */ + readonly message: string; + /** The stack trace, as the browser reports it, or `''` when there isn't one. */ + readonly stack: string; +} +``` + +- Errors from the tab's frames are included, along with dedicated worker + errors in Chromium. +- Navigation, `app.restart()`, other tabs, late entries, and persistent + contexts work the same way as in [`consoleMessages`](#consolemessages). + +| Throws | When | +| --- | --- | +| `APP_NOT_OPEN` | No page is open yet. | +| `ACTION_FAILED` | The call ran past [`actionTimeout`](/reference/config#actiontimeout). | +| `ENGINE_FAILURE` | The browser connection was lost. | + #### `route` Adds an attempt-scoped network route. @@ -1362,7 +1461,8 @@ The package exports these types for typing config helpers and fixtures: `BrowserReleaseContext`, `BrowserProviderDownloads`, `BrowserDownloadContext`, `PlaywrightLiveSurface`, `Browser`, `FrameScreen`, `BrowserExpectation`, `WebRoute`, `RouteFulfillResponse`, -`RouteContinueOverrides`, `RouteMatcher`, `WebResponse`, `Cookie`, `CookieFields`, +`RouteContinueOverrides`, `RouteMatcher`, `WebResponse`, `WebConsoleMessage`, +`WebPageError`, `Cookie`, `CookieFields`, `CookieFilter`, `Dialog`, and `DialogHandler`. The runtime exports are `web`, [`surfaceOf`](#surfaceof), and `test`, @@ -1521,6 +1621,10 @@ export interface Browser extends Expectable { fn: string | ((arg: Arg) => T | Promise), arg: Arg, ): Promise; + /** Returns the console messages logged in the active tab since it opened. Only the latest 200 are kept. */ + consoleMessages(): Promise; + /** Returns the uncaught errors and unhandled rejections in the active tab since it opened. Only the latest 200 are kept. */ + pageErrors(): Promise; /** Adds a script every document runs before the page's own, from the next navigation on. */ addInitScript(script: string | { path: string } | (() => unknown)): Promise; /** Adds an init script function called with one JSON argument. */ diff --git a/packages/web/src/attempt-session.ts b/packages/web/src/attempt-session.ts index 32ab50cead..de89ca93fb 100644 --- a/packages/web/src/attempt-session.ts +++ b/packages/web/src/attempt-session.ts @@ -314,7 +314,10 @@ export class AttemptSession { * of a second tab beside it, which a hosted browser's live view and * recording would show behind the test's. The tab is navigated to * `about:blank` first, so its document runs the context's init scripts - * as a new tab's does. Every later page is a new tab. + * as a new tab's does. Its console messages and page errors are cleared + * first, because a tab's earlier ones are replayed to every new CDP client + * in Chrome. Clearing them after the navigation would drop the init + * scripts' entries from `about:blank`. Every later page is a new tab. */ private async nextPage(context: BrowserContext): Promise { const first = this.firstPage; @@ -322,6 +325,8 @@ export class AttemptSession { if (first && this.options.persistent !== undefined) { const initial = context.pages().find((page) => !page.isClosed()); if (initial !== undefined) { + await initial.clearConsoleMessages(); + await initial.clearPageErrors(); await initial.goto('about:blank'); return initial; } diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 872e611a12..37e1abcb88 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -123,6 +123,33 @@ export interface RouteMatcher { /** The response type `request` returns too, defined in core so the shapes cannot drift. */ export type { WebResponse } from '@e2e-dev/core'; +/** A console message from the page, as returned by `browser.consoleMessages`. */ +export interface WebConsoleMessage { + /** + * The message type, such as `'log'`, `'error'`, or `'warning'` (the type of + * `console.warn`). Most values are Playwright's console message types. The + * rest come from one browser: `'verbose'` from Chromium's own messages, + * `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox, and + * `'image'` and `''` from WebKit. + */ + readonly type: + | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose' + | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'image' + | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' + | 'profile' | 'profileEnd' | 'count' | 'countReset' + | 'time' | 'timeLog' | 'timeEnd' | 'timeStamp' | ''; + /** The message text. */ + readonly text: string; +} + +/** An uncaught error or an unhandled promise rejection from the page, as returned by `browser.pageErrors`. */ +export interface WebPageError { + /** The error message, as the browser reports it. */ + readonly message: string; + /** The stack trace, as the browser reports it, or `''` when there isn't one. */ + readonly stack: string; +} + /** * Reads the body once the response is known and keeps the outcome: a body * that arrived returns a copy of its bytes on every call, a body the browser could not @@ -288,6 +315,10 @@ export interface Browser extends Expectable { fn: string | ((arg: Arg) => T | Promise), arg: Arg, ): Promise; + /** Returns the console messages logged in the active tab since it opened. Only the latest 200 are kept. */ + consoleMessages(): Promise; + /** Returns the uncaught errors and unhandled rejections in the active tab since it opened. Only the latest 200 are kept. */ + pageErrors(): Promise; /** * Adds a script every document runs before the page's own, from the next * navigation on: JavaScript source, a `{ path }` relative to the project @@ -672,6 +703,16 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine }); return decodeEvaluation(report) as T; }, + consoleMessages: () => + surface.guard(context.operation(), 'consoleMessages', async () => { + const messages = await surface.requirePage().consoleMessages({ filter: 'all' }); + return messages.map((message) => ({ type: message.type(), text: message.text() })); + }), + pageErrors: () => + surface.guard(context.operation(), 'pageErrors', async () => { + const errors = await surface.requirePage().pageErrors({ filter: 'all' }); + return errors.map((error) => ({ message: error.message, stack: error.stack ?? '' })); + }), async addInitScript(script: unknown, ...rest: unknown[]) { const source = await testInitScriptSource(script, rest.length === 0 ? undefined : { arg: rest[0] }, (file) => surface.projectPath(file)); await surface.guard(context.operation(), 'addInitScript', () => surface.addInitScript(source)); @@ -981,6 +1022,8 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine title: action, waitForURL: { ...navigationCall, verifies: true, label: patternLabel }, evaluate: action, + consoleMessages: action, + pageErrors: action, addInitScript: { ...action, label: (script) => initScriptLabel(script) }, route: { ...action, label: patternLabel }, unroute: { ...action, label: patternLabel }, diff --git a/packages/web/src/engine-entry.ts b/packages/web/src/engine-entry.ts index dd70460e64..d12a8728c6 100644 --- a/packages/web/src/engine-entry.ts +++ b/packages/web/src/engine-entry.ts @@ -35,6 +35,8 @@ export type { RouteContinueOverrides, RouteFulfillResponse, RouteMatcher, + WebConsoleMessage, + WebPageError, WebResponse, WebRoute, } from './browser.ts'; diff --git a/packages/web/tests/helpers/fixture-app.ts b/packages/web/tests/helpers/fixture-app.ts index a630c5ea39..b9c8acc6e3 100644 --- a/packages/web/tests/helpers/fixture-app.ts +++ b/packages/web/tests/helpers/fixture-app.ts @@ -400,9 +400,51 @@ self.addEventListener('fetch', (event) => { caches.match(event.request).then((cached) => cached ?? Response.error()))); }); `; +/** A page that logs one message of each common console type. */ +const CONSOLE = ` + +Fixture Console + +`; + +/** A page with one unhandled rejection and one error thrown from a timer. */ +const PAGE_ERRORS = ` + +Fixture Page Errors + +`; + +/** A page that throws and rejects with non-Error values. */ +const THROWN_VALUES = ` + +Fixture Thrown Values + +`; + +/** A page whose iframe and dedicated worker each log and throw. */ +const NESTED_CONSOLE = ` + +Fixture Nested Console + + + + +`; const PAGES: Readonly> = { '/': HOME, + '/console': CONSOLE, + '/page-errors': PAGE_ERRORS, + '/thrown-values': THROWN_VALUES, + '/nested-console': NESTED_CONSOLE, '/pointer': POINTER, '/closed-shadow': CLOSED_SHADOW, '/closed-form': CLOSED_FORM, diff --git a/packages/web/tests/integration/console-messages.test.ts b/packages/web/tests/integration/console-messages.test.ts new file mode 100644 index 0000000000..0135a485c3 --- /dev/null +++ b/packages/web/tests/integration/console-messages.test.ts @@ -0,0 +1,172 @@ +/** + * Tests `browser.consoleMessages` and `browser.pageErrors` in a real browser. + * + * Each list holds the active tab's entries since it opened, across + * navigations, frames, and dedicated workers. Each tab has separate lists. + * A persistent browser's first tab drops its messages and errors from before + * the attempt. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; +import { chromium } from 'playwright-core'; +import type { EngineCleanupContext, EngineFixtureContext, EngineHandle, OperationContext } from '@e2e-dev/core/engine'; +import { web, type Browser, type WebOptions } from '../../src/index.ts'; +import { closeRemoteChrome, launchRemoteChrome, type RemoteChrome } from '../helpers/cdp-host.ts'; +import { startFixtureApp, type FixtureApp } from '../helpers/fixture-app.ts'; +import { ignoreTrace, noSecrets } from '../helpers/secrets.ts'; + +function operation(): OperationContext { + return { signal: new AbortController().signal, timeoutMs: 30_000, runId: 'run-console', attemptId: 'c1', origin: 'test' }; +} + +function cleanup(): EngineCleanupContext { + return { signal: new AbortController().signal, timeoutMs: 30_000 }; +} + +describe('browser.consoleMessages and browser.pageErrors', () => { + let app: FixtureApp; + let artifactsDir: string; + let engine: EngineHandle | undefined; + let browser: Browser; + let remote: RemoteChrome | undefined; + + beforeAll(async () => { + app = await startFixtureApp(); + artifactsDir = mkdtempSync(path.join(tmpdir(), 'e2e-console-')); + }); + + afterAll(async () => { + await app.close(); + rmSync(artifactsDir, { recursive: true, force: true }); + }); + + /** Creates an engine with `options`, starts an attempt, and gets its `browser` fixture. */ + async function start(options: WebOptions = {}): Promise { + const started = web(options); + engine = started; + await started.init!({ + runId: 'run-console', targetName: 'web', projectRoot: process.cwd(), + app: { site: '127.0.0.1' }, env: {}, headed: false, + workerSlot: 0, log: () => undefined, signal: new AbortController().signal, + }); + await started.startAttempt!({ attemptId: 'c1', artifactsDir, signal: new AbortController().signal, resolveSecret: noSecrets, ...ignoreTrace }); + browser = started.fixtures!['browser']!({ + operation, + app: { resolveUrl: (url: string) => new URL(url, app.url).href }, + timeouts: { test: 30_000, action: 5_000, assertion: 5_000 }, + expectable: (target: object) => target, + fixture: (_name: string, target: object) => target, + } as unknown as EngineFixtureContext) as Browser; + } + + afterEach(async () => { + const started = engine; + const chrome = remote; + engine = undefined; + remote = undefined; + try { + if (started !== undefined) { + try { + await started.endAttempt!(cleanup()); + } finally { + await started.dispose!(cleanup()); + } + } + } finally { + if (chrome !== undefined) await closeRemoteChrome(chrome); + } + }); + + it('returns each console message with its type and text', async () => { + await start(); + await browser.goto('/console'); + + await expect.poll(() => browser.consoleMessages()).toEqual([ + { type: 'log', text: 'ready' }, + { type: 'warning', text: 'slow' }, + { type: 'error', text: 'broken 42' }, + ]); + }); + + it('returns thrown errors and unhandled rejections with their message and stack', async () => { + await start(); + await browser.goto('/page-errors'); + + await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message).toSorted()).toEqual(['rejected', 'thrown']); + for (const error of await browser.pageErrors()) { + expect(error.stack).toContain(error.message); + } + }); + + it('returns the text of thrown and rejected non-Error values with an empty stack in Chromium', async () => { + await start(); + await browser.goto('/thrown-values'); + + await expect.poll(async () => (await browser.pageErrors()).toSorted((a, b) => a.message.localeCompare(b.message))).toEqual([ + { message: '7', stack: '' }, + { message: 'plain', stack: '' }, + ]); + }); + + it('includes the messages and errors from the tab\'s frames and dedicated workers', async () => { + await start(); + await browser.goto('/nested-console'); + + await expect.poll(async () => (await browser.consoleMessages()).map((message) => message.text).toSorted()).toEqual(['from frame', 'from worker']); + await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message).toSorted()).toEqual(['frame error', 'worker error']); + }); + + it('keeps the messages and errors from earlier documents in the tab', async () => { + await start(); + await browser.goto('/console'); + await browser.goto('/page-errors'); + await expect.poll(() => browser.pageErrors()).toHaveLength(2); + + await browser.goto('/'); + + expect(await browser.consoleMessages()).toHaveLength(3); + expect(await browser.pageErrors()).toHaveLength(2); + }); + + it('keeps a separate list for each tab', async () => { + await start(); + await browser.goto('/console'); + await expect.poll(() => browser.consoleMessages()).toHaveLength(3); + + await browser.newTab(); + + expect(await browser.consoleMessages()).toEqual([]); + await browser.tabs()[0]!.activate(); + expect(await browser.consoleMessages()).toHaveLength(3); + }); + + it('drops entries from before the attempt on a persistent browser while keeping init script entries', async () => { + remote = await launchRemoteChrome(); + const host = await chromium.connectOverCDP(remote.endpoint); + const tab = host.contexts()[0]!.pages()[0]!; + await tab.goto(`${app.url}/page-errors`); + await tab.evaluate(() => console.log('before the attempt')); + await expect.poll(() => tab.pageErrors({ filter: 'all' })).toHaveLength(2); + await expect.poll(async () => (await tab.consoleMessages({ filter: 'all' })).map((message) => message.text())).toContain('before the attempt'); + await host.close(); + + const endpoint = remote.endpoint; + await start({ + connect: { cdpEndpoint: () => endpoint, reconnectEndpoint: () => endpoint }, + initScripts: ["console.log('from init script'); throw new Error('from init script');"], + }); + await browser.goto('/'); + + // FIXME: the remote host runs full Chrome, so it requests /favicon.ico and + // logs a 404. A headless shell doesn't, so that message is left out to + // compare only what the init scripts logged. + const logged = async () => (await browser.consoleMessages()) + .map((message) => message.text) + .filter((text) => !text.startsWith('Failed to load resource')); + await expect.poll(logged).toEqual(['from init script', 'from init script']); + await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message)).toEqual(['from init script', 'from init script']); + }); +}); diff --git a/packages/web/tests/types/console-messages.ts b/packages/web/tests/types/console-messages.ts new file mode 100644 index 0000000000..d799073b74 --- /dev/null +++ b/packages/web/tests/types/console-messages.ts @@ -0,0 +1,22 @@ +/** Checks that `browser.consoleMessages` and `browser.pageErrors` return the expected types and don't take any options. */ +import type { Browser, WebConsoleMessage, WebPageError } from '../../src/index.ts'; + +declare const browser: Browser; +void (browser.consoleMessages() satisfies Promise); +void (browser.pageErrors() satisfies Promise); + +declare const error: WebPageError; +void (error.message satisfies string); +void (error.stack satisfies string); + +declare const message: WebConsoleMessage; +void (message.text satisfies string); +void ('warning' satisfies WebConsoleMessage['type']); +void ('timeLog' satisfies WebConsoleMessage['type']); +// @ts-expect-error `console.warn` has the type 'warning', not 'warn'. +void ('warn' satisfies WebConsoleMessage['type']); + +// @ts-expect-error the lists always hold every entry since the tab opened, so there is no filter. +void browser.consoleMessages({ filter: 'all' }); +// @ts-expect-error the lists always hold every entry since the tab opened, so there is no filter. +void browser.pageErrors({ filter: 'since-navigation' }); diff --git a/packages/web/tests/unit/attempt-session.test.ts b/packages/web/tests/unit/attempt-session.test.ts index d38d5639d4..f27c4401b9 100644 --- a/packages/web/tests/unit/attempt-session.test.ts +++ b/packages/web/tests/unit/attempt-session.test.ts @@ -54,6 +54,8 @@ function target(id: string, response?: Promise<{ targetId: string }>) { once: () => undefined, isClosed: () => false, goto: async () => null, + clearConsoleMessages: async () => undefined, + clearPageErrors: async () => undefined, close: vi.fn(async () => undefined), } as unknown as Page; return { page, send }; diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 306ac415bc..4c9e9c1a50 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -669,6 +669,13 @@ the opener is gone. `tabs()`, `newTab()`, `tab.activate()`, and - `evaluate(fn | source, arg?)`: runs a function or source string in the page, JSON in and out, no closures; a throw in the page is `EVALUATE_FAILED`. +- `consoleMessages()`, `pageErrors()`: the active tab's console messages + (`{ type, text }`) and its uncaught errors and unhandled rejections + (`{ message, stack }`) since it opened. Only the latest 200 are kept. The + lists aren't cleared on navigation. After `app.restart()`, they only have + entries from the new page. Wait for the result on screen with + `expect(locator)` before asserting a list is empty. To wait for a late + entry, use `expect.poll`. - `addInitScript(source | { path } | fn)`, `addInitScript(fn, arg)`: runs before the page's own scripts; call it before `app.open`. `arg` is JSON. - `route(pattern, handler)`, `unroute(pattern)`: intercept requests, newest diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 306ac415bc..4c9e9c1a50 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -669,6 +669,13 @@ the opener is gone. `tabs()`, `newTab()`, `tab.activate()`, and - `evaluate(fn | source, arg?)`: runs a function or source string in the page, JSON in and out, no closures; a throw in the page is `EVALUATE_FAILED`. +- `consoleMessages()`, `pageErrors()`: the active tab's console messages + (`{ type, text }`) and its uncaught errors and unhandled rejections + (`{ message, stack }`) since it opened. Only the latest 200 are kept. The + lists aren't cleared on navigation. After `app.restart()`, they only have + entries from the new page. Wait for the result on screen with + `expect(locator)` before asserting a list is empty. To wait for a late + entry, use `expect.poll`. - `addInitScript(source | { path } | fn)`, `addInitScript(fn, arg)`: runs before the page's own scripts; call it before `app.open`. `arg` is JSON. - `route(pattern, handler)`, `unroute(pattern)`: intercept requests, newest From a30f4480f26adaad79f8ca850d116d4fef82a688 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo Date: Wed, 25 Nov 2026 13:11:50 +0100 Subject: [PATCH 2/4] feat(web): add name to page errors, split at the first colon as Playwright does --- docs/reference/web.mdx | 6 ++++++ packages/web/src/browser.ts | 4 +++- packages/web/tests/helpers/fixture-app.ts | 1 + .../web/tests/integration/console-messages.test.ts | 10 ++++++---- packages/web/tests/types/console-messages.ts | 1 + plugins/e2e/skills/e2e/references/writing-tests.md | 6 +++--- skills/e2e/references/writing-tests.md | 6 +++--- 7 files changed, 23 insertions(+), 11 deletions(-) diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index fb7faa260f..0e476fe523 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -788,6 +788,8 @@ expect(await browser.pageErrors()).toEqual([]); ```ts export interface WebPageError { + /** The error name, such as `'Error'` or `'TypeError'`. */ + readonly name: string; /** The error message, as the browser reports it. */ readonly message: string; /** The stack trace, as the browser reports it, or `''` when there isn't one. */ @@ -795,6 +797,10 @@ export interface WebPageError { } ``` +- The browser's error text is split at its first colon into `name` and + `message`, as Playwright splits it. So a rejected `'Request failed: 500'` + has the name `'Request failed'` and the message `'500'`. A value without + a colon has the name `''`. - Errors from the tab's frames are included, along with dedicated worker errors in Chromium. - Navigation, `app.restart()`, other tabs, late entries, and persistent diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 37e1abcb88..364ae3906c 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -144,6 +144,8 @@ export interface WebConsoleMessage { /** An uncaught error or an unhandled promise rejection from the page, as returned by `browser.pageErrors`. */ export interface WebPageError { + /** The error name, such as `'Error'` or `'TypeError'`. */ + readonly name: string; /** The error message, as the browser reports it. */ readonly message: string; /** The stack trace, as the browser reports it, or `''` when there isn't one. */ @@ -711,7 +713,7 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine pageErrors: () => surface.guard(context.operation(), 'pageErrors', async () => { const errors = await surface.requirePage().pageErrors({ filter: 'all' }); - return errors.map((error) => ({ message: error.message, stack: error.stack ?? '' })); + return errors.map((error) => ({ name: error.name, message: error.message, stack: error.stack ?? '' })); }), async addInitScript(script: unknown, ...rest: unknown[]) { const source = await testInitScriptSource(script, rest.length === 0 ? undefined : { arg: rest[0] }, (file) => surface.projectPath(file)); diff --git a/packages/web/tests/helpers/fixture-app.ts b/packages/web/tests/helpers/fixture-app.ts index b9c8acc6e3..9b84798545 100644 --- a/packages/web/tests/helpers/fixture-app.ts +++ b/packages/web/tests/helpers/fixture-app.ts @@ -423,6 +423,7 @@ const THROWN_VALUES = ` Fixture Thrown Values `; diff --git a/packages/web/tests/integration/console-messages.test.ts b/packages/web/tests/integration/console-messages.test.ts index 0135a485c3..5a8ff0ae2a 100644 --- a/packages/web/tests/integration/console-messages.test.ts +++ b/packages/web/tests/integration/console-messages.test.ts @@ -91,23 +91,25 @@ describe('browser.consoleMessages and browser.pageErrors', () => { ]); }); - it('returns thrown errors and unhandled rejections with their message and stack', async () => { + it('returns thrown errors and unhandled rejections with their name, message, and stack', async () => { await start(); await browser.goto('/page-errors'); await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message).toSorted()).toEqual(['rejected', 'thrown']); for (const error of await browser.pageErrors()) { + expect(error.name).toBe('Error'); expect(error.stack).toContain(error.message); } }); - it('returns the text of thrown and rejected non-Error values with an empty stack in Chromium', async () => { + it('splits thrown and rejected non-Error values at the first colon, with an empty stack in Chromium', async () => { await start(); await browser.goto('/thrown-values'); await expect.poll(async () => (await browser.pageErrors()).toSorted((a, b) => a.message.localeCompare(b.message))).toEqual([ - { message: '7', stack: '' }, - { message: 'plain', stack: '' }, + { name: 'Request failed', message: '500', stack: '' }, + { name: '', message: '7', stack: '' }, + { name: '', message: 'plain', stack: '' }, ]); }); diff --git a/packages/web/tests/types/console-messages.ts b/packages/web/tests/types/console-messages.ts index d799073b74..8a37f1a42f 100644 --- a/packages/web/tests/types/console-messages.ts +++ b/packages/web/tests/types/console-messages.ts @@ -6,6 +6,7 @@ void (browser.consoleMessages() satisfies Promise); void (browser.pageErrors() satisfies Promise); declare const error: WebPageError; +void (error.name satisfies string); void (error.message satisfies string); void (error.stack satisfies string); diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 4c9e9c1a50..cf89111f38 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -671,9 +671,9 @@ the opener is gone. `tabs()`, `newTab()`, `tab.activate()`, and `EVALUATE_FAILED`. - `consoleMessages()`, `pageErrors()`: the active tab's console messages (`{ type, text }`) and its uncaught errors and unhandled rejections - (`{ message, stack }`) since it opened. Only the latest 200 are kept. The - lists aren't cleared on navigation. After `app.restart()`, they only have - entries from the new page. Wait for the result on screen with + (`{ name, message, stack }`) since it opened. Only the latest 200 are + kept. The lists aren't cleared on navigation. After `app.restart()`, they + only have entries from the new page. Wait for the result on screen with `expect(locator)` before asserting a list is empty. To wait for a late entry, use `expect.poll`. - `addInitScript(source | { path } | fn)`, `addInitScript(fn, arg)`: runs diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 4c9e9c1a50..cf89111f38 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -671,9 +671,9 @@ the opener is gone. `tabs()`, `newTab()`, `tab.activate()`, and `EVALUATE_FAILED`. - `consoleMessages()`, `pageErrors()`: the active tab's console messages (`{ type, text }`) and its uncaught errors and unhandled rejections - (`{ message, stack }`) since it opened. Only the latest 200 are kept. The - lists aren't cleared on navigation. After `app.restart()`, they only have - entries from the new page. Wait for the result on screen with + (`{ name, message, stack }`) since it opened. Only the latest 200 are + kept. The lists aren't cleared on navigation. After `app.restart()`, they + only have entries from the new page. Wait for the result on screen with `expect(locator)` before asserting a list is empty. To wait for a late entry, use `expect.poll`. - `addInitScript(source | { path } | fn)`, `addInitScript(fn, arg)`: runs From c0f8a1bcd3e545c10993a83b227c4b1745914d89 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo Date: Wed, 25 Nov 2026 15:28:43 +0100 Subject: [PATCH 3/4] docs(web): reword the console reads' comments and reference entries --- apps/testbed/tests/browser.e2e.ts | 6 ++-- docs/reference/web.mdx | 33 ++++++++++--------- packages/web/src/attempt-session.ts | 8 ++--- packages/web/src/browser.ts | 8 +++-- .../integration/console-messages.test.ts | 4 +-- 5 files changed, 31 insertions(+), 28 deletions(-) diff --git a/apps/testbed/tests/browser.e2e.ts b/apps/testbed/tests/browser.e2e.ts index 44dc08a448..788803533e 100644 --- a/apps/testbed/tests/browser.e2e.ts +++ b/apps/testbed/tests/browser.e2e.ts @@ -52,9 +52,9 @@ test.describe('browser fixture', { platforms: ['web'], tags: ['browser'] }, () = }); test('console messages and page errors read back and clear on restart', async ({ app, browser }) => { - // FIXME: headed Chromium and hosted Chrome request /favicon.ico and log a - // 404 because the playground doesn't serve it. A headless run doesn't, so - // the message is left out to keep the lists the same in every mode. + // FIXME: the playground doesn't serve /favicon.ico, so headed Chromium and + // hosted Chrome log a 404. Headless runs don't, so that message is left + // out to keep the lists the same in every mode. const logged = async () => (await browser.consoleMessages()).filter((message) => !message.text.startsWith('Failed to load resource')); await browser.evaluate(() => { diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index 0e476fe523..cba65efed0 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -267,9 +267,9 @@ What survives: read current geometry and focus with `browser.evaluate` before acting. - Code that uses `surfaceOf(engine)` must read its accessors again after recovery. Playwright objects it kept belong to the disconnected transport. -- The `browser.consoleMessages()` and `browser.pageErrors()` lists only - keep entries from the current document. Chrome doesn't send the earlier - ones again. +- Only entries from the current document are returned by + `browser.consoleMessages()` and `browser.pageErrors()`. Earlier entries + aren't sent again by Chrome. A `browser` provider with `scope: 'attempt'` rides the same persistent context, with the same limits. The lease's `cdpEndpoint` provisions the @@ -731,9 +731,11 @@ export interface WebConsoleMessage { /** * The message type, such as `'log'`, `'error'`, or `'warning'` (the type of * `console.warn`). Most values are Playwright's console message types. The - * rest come from one browser: `'verbose'` from Chromium's own messages, - * `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox, and - * `'image'` and `''` from WebKit. + * rest are browser-specific: + * + * - `'verbose'`: the level of messages from Chromium, not from the page + * - `'countReset'`, `'timeLog'`, and `'timeStamp'`: from Firefox + * - `'image'` and `''`: from WebKit */ readonly type: | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose' @@ -748,14 +750,14 @@ export interface WebConsoleMessage { - Messages from the tab's frames and dedicated workers are included. Messages from service workers aren't. -- The list also has messages the browser writes, such as Chromium's +- Messages the browser writes are included, such as Chromium's `Failed to load resource` for a request that got a 404. Headed Chromium - and hosted Chrome request `/favicon.ico` and log a 404 when the app - doesn't have a favicon, while headless runs don't. + and hosted Chrome request `/favicon.ico` and log a 404 if the app doesn't + have one. Headless runs don't request it. - The list isn't cleared on navigation, so messages from earlier documents in the tab stay in it. - After `app.restart()`, the list only has messages from the new page. -- Each tab has a separate list. To read another tab's list, activate it. +- Each tab has a separate list. Activate a tab to read its list. - A message can show up in the list shortly after it's logged. To wait for one, use [`expect.poll`](/reference/expect#polling-a-value). As in the example, wait for the result on screen before asserting the list is empty. @@ -763,15 +765,14 @@ export interface WebConsoleMessage { On a [persistent context](#recovering-a-cdp-transport), the first tab is reused. Its `consoleMessages` and `pageErrors` entries from before the -attempt are dropped. Entries from the attempt's init scripts are kept. After -the CDP transport reconnects, the lists only have entries from the current -document. +attempt are dropped, while init script entries are kept. After a CDP +reconnect, the lists only have entries from the current document. | Throws | When | | --- | --- | | `APP_NOT_OPEN` | No page is open yet. | -| `ACTION_FAILED` | The call ran past [`actionTimeout`](/reference/config#actiontimeout). | +| `ACTION_FAILED` | The call timed out after [`actionTimeout`](/reference/config#actiontimeout). | | `ENGINE_FAILURE` | The browser connection was lost. | #### `pageErrors` @@ -798,7 +799,7 @@ export interface WebPageError { ``` - The browser's error text is split at its first colon into `name` and - `message`, as Playwright splits it. So a rejected `'Request failed: 500'` + `message`, matching Playwright. So a rejected `'Request failed: 500'` has the name `'Request failed'` and the message `'500'`. A value without a colon has the name `''`. - Errors from the tab's frames are included, along with dedicated worker @@ -809,7 +810,7 @@ export interface WebPageError { | Throws | When | | --- | --- | | `APP_NOT_OPEN` | No page is open yet. | -| `ACTION_FAILED` | The call ran past [`actionTimeout`](/reference/config#actiontimeout). | +| `ACTION_FAILED` | The call timed out after [`actionTimeout`](/reference/config#actiontimeout). | | `ENGINE_FAILURE` | The browser connection was lost. | #### `route` diff --git a/packages/web/src/attempt-session.ts b/packages/web/src/attempt-session.ts index de89ca93fb..f8d0578a57 100644 --- a/packages/web/src/attempt-session.ts +++ b/packages/web/src/attempt-session.ts @@ -314,10 +314,10 @@ export class AttemptSession { * of a second tab beside it, which a hosted browser's live view and * recording would show behind the test's. The tab is navigated to * `about:blank` first, so its document runs the context's init scripts - * as a new tab's does. Its console messages and page errors are cleared - * first, because a tab's earlier ones are replayed to every new CDP client - * in Chrome. Clearing them after the navigation would drop the init - * scripts' entries from `about:blank`. Every later page is a new tab. + * as a new tab's does. Before that navigation, its console messages and + * page errors are cleared, because a tab's earlier ones are replayed to + * every new CDP client in Chrome. Clearing them afterward would drop the + * init scripts' entries from `about:blank`. Every later page is a new tab. */ private async nextPage(context: BrowserContext): Promise { const first = this.firstPage; diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 364ae3906c..1b6bf8bcb4 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -128,9 +128,11 @@ export interface WebConsoleMessage { /** * The message type, such as `'log'`, `'error'`, or `'warning'` (the type of * `console.warn`). Most values are Playwright's console message types. The - * rest come from one browser: `'verbose'` from Chromium's own messages, - * `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox, and - * `'image'` and `''` from WebKit. + * rest are browser-specific: + * + * - `'verbose'`: the level of messages from Chromium, not from the page + * - `'countReset'`, `'timeLog'`, and `'timeStamp'`: from Firefox + * - `'image'` and `''`: from WebKit */ readonly type: | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose' diff --git a/packages/web/tests/integration/console-messages.test.ts b/packages/web/tests/integration/console-messages.test.ts index 5a8ff0ae2a..c58021c6d0 100644 --- a/packages/web/tests/integration/console-messages.test.ts +++ b/packages/web/tests/integration/console-messages.test.ts @@ -3,8 +3,8 @@ * * Each list holds the active tab's entries since it opened, across * navigations, frames, and dedicated workers. Each tab has separate lists. - * A persistent browser's first tab drops its messages and errors from before - * the attempt. + * On a persistent browser's first tab, entries from before the attempt are + * dropped. */ import { mkdtempSync, rmSync } from 'node:fs'; From c4d74a4923a15cdaece1ec734d30b6521a18dee2 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo Date: Wed, 25 Nov 2026 15:43:22 +0100 Subject: [PATCH 4/4] docs(web): use the review's wording for the console reads' comments and entries --- apps/testbed/tests/browser.e2e.ts | 4 ++-- docs/reference/web.mdx | 23 +++++++++++------------ packages/web/src/attempt-session.ts | 6 +++--- packages/web/src/browser.ts | 6 +++--- 4 files changed, 19 insertions(+), 20 deletions(-) diff --git a/apps/testbed/tests/browser.e2e.ts b/apps/testbed/tests/browser.e2e.ts index 788803533e..1bef739145 100644 --- a/apps/testbed/tests/browser.e2e.ts +++ b/apps/testbed/tests/browser.e2e.ts @@ -53,8 +53,8 @@ test.describe('browser fixture', { platforms: ['web'], tags: ['browser'] }, () = test('console messages and page errors read back and clear on restart', async ({ app, browser }) => { // FIXME: the playground doesn't serve /favicon.ico, so headed Chromium and - // hosted Chrome log a 404. Headless runs don't, so that message is left - // out to keep the lists the same in every mode. + // hosted Chrome log a 404. Headless runs don't, so that message is + // filtered out to keep the lists the same in every mode. const logged = async () => (await browser.consoleMessages()).filter((message) => !message.text.startsWith('Failed to load resource')); await browser.evaluate(() => { diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index cba65efed0..f8b42e646b 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -267,9 +267,8 @@ What survives: read current geometry and focus with `browser.evaluate` before acting. - Code that uses `surfaceOf(engine)` must read its accessors again after recovery. Playwright objects it kept belong to the disconnected transport. -- Only entries from the current document are returned by - `browser.consoleMessages()` and `browser.pageErrors()`. Earlier entries - aren't sent again by Chrome. +- `browser.consoleMessages()` and `browser.pageErrors()` only have entries + from the current document. Chrome doesn't send earlier ones again. A `browser` provider with `scope: 'attempt'` rides the same persistent context, with the same limits. The lease's `cdpEndpoint` provisions the @@ -733,9 +732,9 @@ export interface WebConsoleMessage { * `console.warn`). Most values are Playwright's console message types. The * rest are browser-specific: * - * - `'verbose'`: the level of messages from Chromium, not from the page - * - `'countReset'`, `'timeLog'`, and `'timeStamp'`: from Firefox - * - `'image'` and `''`: from WebKit + * - `'verbose'` from browser messages in Chromium + * - `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox + * - `'image'` and `''` from WebKit */ readonly type: | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose' @@ -750,10 +749,10 @@ export interface WebConsoleMessage { - Messages from the tab's frames and dedicated workers are included. Messages from service workers aren't. -- Messages the browser writes are included, such as Chromium's - `Failed to load resource` for a request that got a 404. Headed Chromium - and hosted Chrome request `/favicon.ico` and log a 404 if the app doesn't - have one. Headless runs don't request it. +- Browser messages are included, such as Chromium's + `Failed to load resource` on a 404. If the app doesn't have a favicon, + headed Chromium and hosted Chrome request `/favicon.ico` and log a 404. + Headless runs don't. - The list isn't cleared on navigation, so messages from earlier documents in the tab stay in it. - After `app.restart()`, the list only has messages from the new page. @@ -772,7 +771,7 @@ reconnect, the lists only have entries from the current document. | Throws | When | | --- | --- | | `APP_NOT_OPEN` | No page is open yet. | -| `ACTION_FAILED` | The call timed out after [`actionTimeout`](/reference/config#actiontimeout). | +| `ACTION_FAILED` | Timed out after [`actionTimeout`](/reference/config#actiontimeout). | | `ENGINE_FAILURE` | The browser connection was lost. | #### `pageErrors` @@ -810,7 +809,7 @@ export interface WebPageError { | Throws | When | | --- | --- | | `APP_NOT_OPEN` | No page is open yet. | -| `ACTION_FAILED` | The call timed out after [`actionTimeout`](/reference/config#actiontimeout). | +| `ACTION_FAILED` | Timed out after [`actionTimeout`](/reference/config#actiontimeout). | | `ENGINE_FAILURE` | The browser connection was lost. | #### `route` diff --git a/packages/web/src/attempt-session.ts b/packages/web/src/attempt-session.ts index f8d0578a57..1a52205ea5 100644 --- a/packages/web/src/attempt-session.ts +++ b/packages/web/src/attempt-session.ts @@ -315,9 +315,9 @@ export class AttemptSession { * recording would show behind the test's. The tab is navigated to * `about:blank` first, so its document runs the context's init scripts * as a new tab's does. Before that navigation, its console messages and - * page errors are cleared, because a tab's earlier ones are replayed to - * every new CDP client in Chrome. Clearing them afterward would drop the - * init scripts' entries from `about:blank`. Every later page is a new tab. + * page errors are cleared because Chrome replays earlier ones to every new + * CDP client. Clearing them after would drop the init scripts' entries from + * `about:blank`. Every later page is a new tab. */ private async nextPage(context: BrowserContext): Promise { const first = this.firstPage; diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 1b6bf8bcb4..144dcc772b 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -130,9 +130,9 @@ export interface WebConsoleMessage { * `console.warn`). Most values are Playwright's console message types. The * rest are browser-specific: * - * - `'verbose'`: the level of messages from Chromium, not from the page - * - `'countReset'`, `'timeLog'`, and `'timeStamp'`: from Firefox - * - `'image'` and `''`: from WebKit + * - `'verbose'` from browser messages in Chromium + * - `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox + * - `'image'` and `''` from WebKit */ readonly type: | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose'