playwright_custom_user_agent
Set a custom User Agent in Playwright browser automation to simulate different devices or browsers, enabling tailored web interactions during 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:12-40 (handler)CustomUserAgentTool class implementing the tool's execute method, which validates the current user agent matches the provided one.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:331-341 (schema)Tool definition in createToolDefinitions(), including name, description, and inputSchema requiring '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:514-515 (registration)Registration and dispatch in handleToolCall switch statement, calling CustomUserAgentTool.executecase "playwright_custom_user_agent": return await customUserAgentTool.execute(args, context);
- src/toolHandler.ts:429-436 (handler)Special handling in ensureBrowser to set custom userAgent in browser context when this tool is called.const browserSettings = { viewport: { width: args.width, height: args.height }, userAgent: name === "playwright_custom_user_agent" ? args.userAgent : undefined, headless: args.headless, browserType: args.browserType || 'chromium'
- Code generation helper method to produce Playwright code for setting user agent in test files.private generateCustomUserAgentStep(parameters: Record<string, unknown>): string { const { userAgent } = parameters; return ` // Set custom user agent await context.setUserAgent('${userAgent}');`; }