playwright_custom_user_agent
Set a custom User Agent for the Playwright browser instance to simulate specific devices or browsers during web interactions, testing, or scraping tasks.
Instructions
Set a custom User Agent for the browser
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| userAgent | Yes | Custom User Agent for the Playwright browser instance |
Implementation Reference
- src/tools/browser/useragent.ts:9-40 (handler)The CustomUserAgentTool class implements the core handler logic for the 'playwright_custom_user_agent' tool. It validates that the current page's user agent matches the requested one, confirming successful application during browser launch./** * Tool for validating custom User Agent settings */ export class CustomUserAgentTool extends BrowserToolBase { /** * Execute the custom user agent tool */ async execute(args: CustomUserAgentArgs, context: ToolContext): Promise<ToolResponse> { return this.safeExecute(context, async (page) => { if (!args.userAgent) { return createErrorResponse("Missing required parameter: userAgent must be provided"); } try { const currentUserAgent = await page.evaluate(() => navigator.userAgent); if (currentUserAgent !== args.userAgent) { const messages = [ "Page was already initialized with a different User Agent.", `Requested: ${args.userAgent}`, `Current: ${currentUserAgent}` ]; return createErrorResponse(messages.join('\n')); } return createSuccessResponse("User Agent validation successful"); } catch (error) { return createErrorResponse(`Failed to validate User Agent: ${(error as Error).message}`); } }); } }
- src/tools.ts:306-316 (schema)Tool schema definition including name, description, and input schema requiring a 'userAgent' string.{ name: "playwright_custom_user_agent", description: "Set a custom User Agent for the browser", inputSchema: { type: "object", properties: { userAgent: { type: "string", description: "Custom User Agent for the Playwright browser instance" } }, required: ["userAgent"], }, },
- src/toolHandler.ts:492-493 (registration)Registration and dispatch in the main handleToolCall switch statement, delegating execution to the CustomUserAgentTool instance.case "playwright_custom_user_agent": return await customUserAgentTool.execute(args, context);
- src/toolHandler.ts:298-299 (registration)Instantiation of the CustomUserAgentTool instance during tool initialization.if (!customUserAgentTool) customUserAgentTool = new CustomUserAgentTool(server);
- Helper function in codegen generator that produces Playwright code for the custom user agent action.case 'playwright_custom_user_agent': return this.generateCustomUserAgentStep(parameters); default: console.warn(`Unsupported tool: ${toolName}`); return null; } } private generateNavigateStep(parameters: Record<string, unknown>): string { const { url, waitUntil } = parameters; const options = waitUntil ? `, { waitUntil: '${waitUntil}' }` : ''; return ` // Navigate to URL await page.goto('${url}'${options});`; } private generateFillStep(parameters: Record<string, unknown>): string { const { selector, value } = parameters; return ` // Fill input field await page.fill('${selector}', '${value}');`; } private generateClickStep(parameters: Record<string, unknown>): string { const { selector } = parameters; return ` // Click element await page.click('${selector}');`; } private generateScreenshotStep(parameters: Record<string, unknown>): string { const { name, fullPage = false, path } = parameters; const options = []; if (fullPage) options.push('fullPage: true'); if (path) options.push(`path: '${path}'`); const optionsStr = options.length > 0 ? `, { ${options.join(', ')} }` : ''; return ` // Take screenshot await page.screenshot({ path: '${name}.png'${optionsStr} });`; } private generateExpectResponseStep(parameters: Record<string, unknown>): string { const { url, id } = parameters; return ` // Wait for response const ${id}Response = page.waitForResponse('${url}');`; } private generateAssertResponseStep(parameters: Record<string, unknown>): string { const { id, value } = parameters; const assertion = value ? `\n const responseText = await ${id}Response.text();\n expect(responseText).toContain('${value}');` : `\n expect(${id}Response.ok()).toBeTruthy();`; return ` // Assert response${assertion}`; } private generateHoverStep(parameters: Record<string, unknown>): string { const { selector } = parameters; return ` // Hover over element await page.hover('${selector}');`; } private generateSelectStep(parameters: Record<string, unknown>): string { const { selector, value } = parameters; return ` // Select option await page.selectOption('${selector}', '${value}');`; } private generateCustomUserAgentStep(parameters: Record<string, unknown>): string { const { userAgent } = parameters; return ` // Set custom user agent await context.setUserAgent('${userAgent}');`; }