Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/playwright-core/src/tools/backend/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -69,14 +70,16 @@ 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,
compact: false,
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));
Expand Down
3 changes: 2 additions & 1 deletion packages/playwright-core/src/tools/cli-daemon/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 53 additions & 0 deletions tests/mcp/evaluate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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',
Expand All @@ -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.',
});
});
Loading