playwright_evaluate
Execute JavaScript in the browser console to automate web interactions, extract data, or manipulate web elements using the Playwright MCP Server.
Instructions
Execute JavaScript in the browser console
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| script | Yes | JavaScript code to execute |
Implementation Reference
- src/toolsHandler.ts:274-318 (handler)Switch case handling the 'playwright_evaluate' tool: executes JavaScript in the browser page context using page.evaluate, overrides console methods to capture logs, and returns the result along with console output.case "playwright_evaluate": try { const result = await page!.evaluate((script) => { const logs: string[] = []; const originalConsole = { ...console }; ['log', 'info', 'warn', 'error'].forEach(method => { (console as any)[method] = (...args: any[]) => { logs.push(`[${method}] ${args.join(' ')}`); (originalConsole as any)[method](...args); }; }); try { const result = eval(script); Object.assign(console, originalConsole); return { result, logs }; } catch (error) { Object.assign(console, originalConsole); throw error; } }, args.script); return { toolResult: { content: [ { type: "text", text: `Execution result:\n${JSON.stringify(result.result, null, 2)}\n\nConsole output:\n${result.logs.join('\n')}`, }, ], isError: false, }, }; } catch (error) { return { toolResult: { content: [{ type: "text", text: `Script execution failed: ${(error as Error).message}`, }], isError: true, }, }; }
- src/tools.ts:79-89 (schema)Tool schema definition for 'playwright_evaluate', specifying name, description, and input schema requiring a 'script' string.{ name: "playwright_evaluate", description: "Execute JavaScript in the browser console", inputSchema: { type: "object", properties: { script: { type: "string", description: "JavaScript code to execute" }, }, required: ["script"], }, },
- src/requestHandler.ts:59-62 (registration)Registration of the tool list handler, which returns all tools including 'playwright_evaluate' from createToolDefinitions().// List tools handler server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools, }));
- src/requestHandler.ts:65-67 (registration)Registration of the tool call handler, which dispatches to handleToolCall for 'playwright_evaluate' and other tools.server.setRequestHandler(CallToolRequestSchema, async (request) => handleToolCall(request.params.name, request.params.arguments ?? {}, server) );
- src/tools.ts:152-160 (helper)BROWSER_TOOLS array listing 'playwright_evaluate' to trigger browser launch when this tool is called.export const BROWSER_TOOLS = [ "playwright_navigate", "playwright_screenshot", "playwright_click", "playwright_fill", "playwright_select", "playwright_hover", "playwright_evaluate" ];