Skip to main content
Glama

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
NameRequiredDescriptionDefault
userAgentYesCustom User Agent for the Playwright browser instance

Implementation Reference

  • 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}`);
          }
        });
      }
    } 
  • 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"],
      },
    },
  • Registration and dispatch in handleToolCall switch statement, calling CustomUserAgentTool.execute
    case "playwright_custom_user_agent":
      return await customUserAgentTool.execute(args, context);
  • 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}');`;
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/executeautomation/mcp-playwright'

If you have feedback or need assistance with the MCP directory API, please join our Discord server