focus
Focus on a webpage element using its CSS selector to enable user interaction or input, with configurable timeout and tab selection for automated browser control.
Instructions
Focus an element on the page
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| selector | Yes | CSS selector for the element | |
| timeout | No | Timeout in milliseconds | |
| tabId | No | Tab ID to operate on (uses active tab if not specified) |
Implementation Reference
- src/tools/interaction.ts:168-195 (handler)The handler function that implements the 'focus' tool logic: gets the page for the tab, waits for the selector to appear, calls element.focus() using Puppeteer, handles selector not found and other errors, returns success with focused confirmation.async ({ selector, timeout, tabId }) => { const pageResult = await getPageForOperation(tabId); if (!pageResult.success) { return handleResult(pageResult); } const page = pageResult.data; const timeoutMs = timeout ?? getDefaultTimeout(); try { const element = await page.waitForSelector(selector, { timeout: timeoutMs, }); if (!element) { return handleResult(err(selectorNotFound(selector))); } await element.focus(); return handleResult(ok({ focused: true, selector })); } catch (error) { if (error instanceof Error && error.message.includes('waiting for selector')) { return handleResult(err(selectorNotFound(selector))); } return handleResult(err(normalizeError(error))); } }
- src/schemas.ts:81-85 (schema)Zod schema defining the input parameters for the 'focus' tool: CSS selector (required), optional timeout in ms, optional tabId.export const focusSchema = z.object({ selector: selectorSchema, timeout: timeoutSchema, tabId: tabIdSchema, });
- src/tools/interaction.ts:164-196 (registration)Registers the 'focus' tool on the MCP server within the registerInteractionTools function, specifying name, description, input schema, and handler.server.tool( 'focus', 'Focus an element on the page', focusSchema.shape, async ({ selector, timeout, tabId }) => { const pageResult = await getPageForOperation(tabId); if (!pageResult.success) { return handleResult(pageResult); } const page = pageResult.data; const timeoutMs = timeout ?? getDefaultTimeout(); try { const element = await page.waitForSelector(selector, { timeout: timeoutMs, }); if (!element) { return handleResult(err(selectorNotFound(selector))); } await element.focus(); return handleResult(ok({ focused: true, selector })); } catch (error) { if (error instanceof Error && error.message.includes('waiting for selector')) { return handleResult(err(selectorNotFound(selector))); } return handleResult(err(normalizeError(error))); } } );
- src/server.ts:24-24 (registration)Top-level call to register interaction tools (including 'focus') on the main MCP server instance.registerInteractionTools(server);