execute_js
Execute JavaScript code on webpages to automate browser interactions, modify content, or extract data through programmatic control.
Instructions
Execute JavaScript code on a webpage
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | The URL to navigate to | |
| script | Yes | The JavaScript code to execute | |
| steps | No | Comma-separated actions or sentences describing steps to take after page load (e.g., "click #submit, scroll down" or "Fill the login form and submit") |
Implementation Reference
- src/browser_handler.py:222-248 (handler)Handler for the 'execute_js' command. Navigates to the specified URL using an AI agent for optional steps, then executes the provided JavaScript script on the page and returns the result.elif command == 'execute_js': if not args.get('url') or not args.get('script'): return { 'success': False, 'error': 'URL and script are required for execute_js command' } task = f"1. Go to {args['url']}" if args.get('steps'): steps = args['steps'].split(',') for i, step in enumerate(steps, 2): task += f"\n{i}. {step.strip()}" task += f"\n{len(steps) + 2}. Execute JavaScript: {args['script']}" else: task += f"\n2. Execute JavaScript: {args['script']}" use_vision = os.getenv('USE_VISION', 'false').lower() == 'true' agent = Agent(task=task, llm=llm, use_vision=use_vision, browser_context=context) await agent.run() try: result = await context.execute_javascript(args['script']) return { 'success': True, 'result': result } finally: await context.close()
- src/index.ts:192-212 (registration)Registration of the 'execute_js' tool in the MCP server, including name, description, and input schema definition.{ name: 'execute_js', description: 'Execute JavaScript code on a webpage', inputSchema: { type: 'object', properties: { url: { type: 'string', description: 'The URL to navigate to', }, script: { type: 'string', description: 'The JavaScript code to execute', }, steps: { type: 'string', description: 'Comma-separated actions or sentences describing steps to take after page load (e.g., "click #submit, scroll down" or "Fill the login form and submit")', }, }, required: ['url', 'script'], },
- src/index.ts:252-257 (schema)Input validation specifically for the 'execute_js' tool, ensuring the script argument is a string.if (request.params.name === 'execute_js' && typeof args.script !== 'string') { throw new McpError( ErrorCode.InvalidParams, 'Script must be a string' ); }
- src/browser_handler.py:242-248 (helper)Core execution of the JavaScript using the browser context's execute_javascript method.result = await context.execute_javascript(args['script']) return { 'success': True, 'result': result } finally: await context.close()