Skip to main content
Glama

wait_for_element

Read-only

Wait for an element to become visible, hidden, attached, or detached. Replaces unreliable sleep() calls for dynamic content. Supports CSS selectors and testid shortcuts.

Instructions

Wait for an element to reach a specific state (visible, hidden, attached, detached). Better than sleep() for waiting on dynamic content. Returns duration and current element status. Supports testid shortcuts (e.g., 'testid:submit-button').

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector, text selector, or testid shorthand (e.g., 'testid:submit-button', '#loading-spinner')
stateNoState to wait for: 'visible' (default), 'hidden', 'attached', 'detached'
timeoutNoMaximum time to wait in milliseconds (default: 10000)

Implementation Reference

  • The execute() method that implements the wait_for_element tool logic. Uses Playwright's locator.waitFor() to wait for an element to reach a specified state (visible, hidden, attached, detached). Returns duration and current element status, or a timeout error.
      async execute(args: WaitForElementArgs, context: ToolContext): Promise<ToolResponse> {
        return this.safeExecute(context, async (page) => {
          const { selector, state = 'visible', timeout = 10000 } = args;
    
          const locator = await this.createScopedLocator(page, selector);
    
          const startTime = Date.now();
    
          try {
            await locator.waitFor({ state, timeout });
            const duration = ((Date.now() - startTime) / 1000).toFixed(1);
    
            // Check current state
            const isVisible = await locator.isVisible().catch(() => false);
            const count = await locator.count();
            const exists = count > 0;
    
            const statusLines = [
              `✓ Element ${state} after ${duration}s`,
              `Now: ${isVisible ? '✓ visible' : '✗ hidden'}, ${exists ? '✓ exists' : '✗ not found'}`
            ];
    
            return {
              content: [{ type: 'text', text: statusLines.join('\n') }],
              isError: false,
            };
          } catch (error) {
            const duration = ((Date.now() - startTime) / 1000).toFixed(1);
            const errorMessage = error instanceof Error ? error.message : String(error);
    
            return {
              content: [{
                type: 'text',
                text: `✗ Timeout after ${duration}s waiting for element to be ${state}\nError: ${errorMessage}`
              }],
              isError: true,
            };
          }
        });
      }
    }
  • The WaitForElementArgs interface and inputSchema definition defining the tool's input: selector (required), state (optional, enum of visible/hidden/attached/detached, default 'visible'), and timeout (optional, default 10000ms).
    export interface WaitForElementArgs {
      selector: string;
      state?: 'visible' | 'hidden' | 'attached' | 'detached';
      timeout?: number;
    }
    
    export class WaitForElementTool extends BrowserToolBase {
      static getMetadata(sessionConfig?: SessionConfig): ToolMetadata {
        return {
          name: "wait_for_element",
          description: "Wait for an element to reach a specific state (visible, hidden, attached, detached). Better than sleep() for waiting on dynamic content. Returns duration and current element status. Supports testid shortcuts (e.g., 'testid:submit-button').",
          annotations: ANNOTATIONS.readOnly,
          inputSchema: {
            type: "object",
            properties: {
              selector: {
                type: "string",
                description: "CSS selector, text selector, or testid shorthand (e.g., 'testid:submit-button', '#loading-spinner')"
              },
              state: {
                type: "string",
                description: "State to wait for: 'visible' (default), 'hidden', 'attached', 'detached'",
                enum: ["visible", "hidden", "attached", "detached"]
              },
              timeout: {
                type: "number",
                description: "Maximum time to wait in milliseconds (default: 10000)"
              }
            },
            required: ["selector"],
          },
        };
  • The WaitForElementTool class definition extending BrowserToolBase, implementing the ToolHandler interface with getMetadata() and execute() methods.
    export class WaitForElementTool extends BrowserToolBase {
      static getMetadata(sessionConfig?: SessionConfig): ToolMetadata {
        return {
          name: "wait_for_element",
          description: "Wait for an element to reach a specific state (visible, hidden, attached, detached). Better than sleep() for waiting on dynamic content. Returns duration and current element status. Supports testid shortcuts (e.g., 'testid:submit-button').",
          annotations: ANNOTATIONS.readOnly,
          inputSchema: {
            type: "object",
            properties: {
              selector: {
                type: "string",
                description: "CSS selector, text selector, or testid shorthand (e.g., 'testid:submit-button', '#loading-spinner')"
              },
              state: {
                type: "string",
                description: "State to wait for: 'visible' (default), 'hidden', 'attached', 'detached'",
                enum: ["visible", "hidden", "attached", "detached"]
              },
              timeout: {
                type: "number",
                description: "Maximum time to wait in milliseconds (default: 10000)"
              }
            },
            required: ["selector"],
          },
        };
      }
  • Import and registration of WaitForElementTool in the BROWSER_TOOL_CLASSES array at lines 50 (import) and 102 (registration in the 'Waiting' section).
    import { WaitForElementTool } from './waiting/wait_for_element.js';
    import { WaitForNetworkIdleTool } from './waiting/wait_for_network_idle.js';
    
    export const BROWSER_TOOL_CLASSES: ToolClass[] = [
      // Navigation (5)
      NavigateTool,
      GoHistoryTool,
      ScrollToElementTool,
      ScrollByTool,
    
      // Lifecycle (2)
      CloseTool,
      SetColorSchemeTool,
    
      // Interaction (7)
      ClickTool,
      FillTool,
      SelectTool,
      HoverTool,
      UploadFileTool,
      DragTool,
      PressKeyTool,
    
      // Content (3)
      ScreenshotTool,
      GetTextTool,
      GetHtmlTool,
    
      // Inspection (10)
      InspectDomTool,
      GetTestIdsTool,
      QuerySelectorTool,
      FindByTextTool,
      CheckVisibilityTool,
      CompareElementAlignmentTool,
      InspectAncestorsTool,
      ElementExistsTool,
      MeasureElementTool,
      GetComputedStylesTool,
    
      // Evaluation (1)
      EvaluateTool,
    
      // Console (2)
      GetConsoleLogsTool,
      ClearConsoleLogsTool,
    
      // Network (2)
      ListNetworkRequestsTool,
      GetRequestDetailsTool,
    
      // Waiting (2)
      WaitForElementTool,
      WaitForNetworkIdleTool,
    ];
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations (readOnlyHint=true) indicate no destructive side effects. Description adds that it returns duration and status, and supports testid shortcuts. No contradictions. Lacks detail on timeout behavior, but acceptable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three sentences, front-loaded with main purpose, then differentiator, then additional features. No redundancy. Efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With 3 params, no output schema, description covers purpose, parameters, return info, and usage suggestion. Could mention timeout behavior or error handling, but not essential. Adequate for most use cases.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema covers all 3 parameters with 100% description coverage. Description adds value by explaining testid shorthand for selector and clarifying default state. Minor extra beyond schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states it waits for an element to reach a specific state (visible, hidden, attached, detached). Distinguishes from sleep() and mentions return value (duration, status) and testid shortcuts. No ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly recommends using this instead of sleep() for dynamic content. Does not mention when not to use, but context from sibling tools suggests alternative waiting tools (e.g., wait_for_network_idle) for other cases. Adequate guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/antonzherdev/mcp-web-inspector'

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