diff --git a/packages/playwright-core/src/tools/backend/evaluate.ts b/packages/playwright-core/src/tools/backend/evaluate.ts index 581969a225ec1..e8e95f91a4c93 100644 --- a/packages/playwright-core/src/tools/backend/evaluate.ts +++ b/packages/playwright-core/src/tools/backend/evaluate.ts @@ -27,6 +27,7 @@ import type { Tab } from './tab'; const evaluateSchema = optionalElementSchema.extend({ function: z.string().describe('() => { /* code */ } or (element) => { /* code */ } when element is provided'), filename: z.string().optional().describe('File name to save the result to. Relative file names are resolved against the workspace root. If not provided, result is returned as text.'), + format: z.enum(['json', 'string', 'default']).optional().describe('Result format: "json" uses JSON.stringify, "string" uses String, and "default" (the default) uses JSON for JSON-compatible values and JavaScript inspection otherwise. Applies to both inline and file results, regardless of filename extension.'), }); const evaluate = defineTabTool({ @@ -69,7 +70,7 @@ const evaluate = defineTabTool({ else response.addCode(`await page.evaluate(${escapeWithQuotes(codeExpression)});`); - const text = isJSONValue(evalResult.result) ? JSON.stringify(evalResult.result, null, 2) : inspect(evalResult.result, { + const text = params.format === 'string' ? String(evalResult.result) : params.format === 'json' || isJSONValue(evalResult.result) ? JSON.stringify(evalResult.result, null, 2) : inspect(evalResult.result, { depth: null, maxArrayLength: null, maxStringLength: null, @@ -77,6 +78,8 @@ const evaluate = defineTabTool({ colors: false, customInspect: false, }); + if (text === undefined) + throw new Error('Evaluation result cannot be represented as JSON.'); await response.addResult('Evaluation result', text, { prefix: 'result', ext: 'json', suggestedFilename: params.filename }); }).catch(e => { response.addError(e instanceof Error ? e.message : String(e)); diff --git a/packages/playwright-core/src/tools/cli-daemon/commands.ts b/packages/playwright-core/src/tools/cli-daemon/commands.ts index 571eecf060c64..53d031575aecd 100644 --- a/packages/playwright-core/src/tools/cli-daemon/commands.ts +++ b/packages/playwright-core/src/tools/cli-daemon/commands.ts @@ -447,9 +447,10 @@ const evaluate = declareCommand({ }), options: z.object({ filename: z.string().optional().describe('Save evaluation result to a file instead of returning it in the response.'), + format: z.enum(['json', 'string', 'default']).optional().describe('Result format: json (JSON.stringify), string (String), or default (JSON for JSON-compatible values, JavaScript inspection otherwise).'), }), toolName: 'browser_evaluate', - toolParams: ({ func, target, filename }) => ({ function: func, filename, target }), + toolParams: ({ func, target, filename, format }) => ({ function: func, filename, target, format }), }); const dialogAccept = declareCommand({ diff --git a/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md b/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md index eecd55737cf36..b2becf92aa688 100644 --- a/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md +++ b/packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md @@ -55,6 +55,7 @@ playwright-cli find --regex "/sign (in|up)/i" # save results to a file when a query produces too many matches playwright-cli find "Add" --filename=results.md playwright-cli eval "document.title" +playwright-cli eval "document.body.innerText" --format=string --filename=page.txt playwright-cli eval "el => el.textContent" e5 # get element id, class, or any attribute not visible in the snapshot playwright-cli eval "el => el.id" e5 diff --git a/tests/mcp/evaluate.spec.ts b/tests/mcp/evaluate.spec.ts index 424cea8c8eed2..1368f7c9df088 100644 --- a/tests/mcp/evaluate.spec.ts +++ b/tests/mcp/evaluate.spec.ts @@ -14,6 +14,8 @@ * limitations under the License. */ +import fs from 'fs'; + import { test, expect } from './fixtures'; test('browser_evaluate', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43752' } }, async ({ client, server }) => { @@ -139,6 +141,11 @@ test('browser_evaluate object', { annotation: { type: 'issue', description: 'htt name: 'browser_evaluate', arguments: { function: '() => window.evaluationCount' }, })).toHaveResponse({ result: '1' }); + + expect(await client.callTool({ + name: 'browser_evaluate', + arguments: { function: `() => new Date('2026-01-01T00:00:00Z')`, format: 'json' }, + })).toHaveResponse({ result: '"2026-01-01T00:00:00.000Z"' }); }); test('browser_evaluate expression', async ({ client, server }) => { @@ -200,6 +207,44 @@ test('browser_evaluate expression', async ({ client, server }) => { }); }); +test('browser_evaluate format', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/44295' } }, async ({ client, server }, testInfo) => { + await client.callTool({ + name: 'browser_navigate', + arguments: { url: server.HELLO_WORLD }, + }); + + const expression = `() => 'first line\\nsecond line\\n'`; + expect(await client.callTool({ + name: 'browser_evaluate', + arguments: { function: expression, filename: 'eval-out.txt' }, + })).toHaveResponse({ + result: expect.stringContaining('eval-out.txt'), + }); + expect(await fs.promises.readFile(testInfo.outputPath('eval-out.txt'), 'utf8')).toBe(JSON.stringify('first line\nsecond line\n')); + + await client.callTool({ + name: 'browser_evaluate', + arguments: { function: expression, filename: 'eval-out.json', format: 'string' }, + }); + expect(await fs.promises.readFile(testInfo.outputPath('eval-out.json'), 'utf8')).toBe('first line\nsecond line\n'); + + expect(await client.callTool({ + name: 'browser_evaluate', + arguments: { function: expression, format: 'string' }, + })).toHaveResponse({ result: 'first line\nsecond line' }); + + expect(await client.callTool({ + name: 'browser_evaluate', + arguments: { function: expression, format: 'default' }, + })).toHaveResponse({ result: JSON.stringify('first line\nsecond line\n') }); + + await client.callTool({ + name: 'browser_evaluate', + arguments: { function: `() => ({ a: 1 })`, filename: 'eval-object.txt', format: 'json' }, + }); + expect(await fs.promises.readFile(testInfo.outputPath('eval-object.txt'), 'utf8')).toBe(JSON.stringify({ a: 1 }, null, 2)); +}); + test('browser_evaluate (error)', async ({ client, server }) => { expect(await client.callTool({ name: 'browser_navigate', @@ -220,4 +265,12 @@ test('browser_evaluate (error)', async ({ client, server }) => { // Check for common error patterns across browsers const errorText = result.content?.[0]?.text || ''; expect(errorText).toMatch(/not defined|Can't find variable/); + + expect(await client.callTool({ + name: 'browser_evaluate', + arguments: { function: '() => undefined', format: 'json' }, + })).toHaveResponse({ + isError: true, + error: 'Evaluation result cannot be represented as JSON.', + }); });