Skip to main content

Overview

The act() method allows you to perform browser actions using natural language instructions. It uses AI to understand your intent, locate the appropriate elements on the page, and execute the action.

Method Signature

act(instruction: string | Action, options?: ActOptions): Promise<ActResult>

Parameters

instruction
string | Action
required
The action you want to perform, described in natural language (e.g., “click the login button”). Can also accept an Action object from observe() for cached/preview actions.
options
ActOptions
Optional configuration for the action.

Return Value

Returns a Promise<ActResult> with the following structure:
interface ActResult {
  success: boolean;           // Whether the action succeeded
  message: string;            // Descriptive message about the result
  actionDescription: string;  // Description of what was attempted
  actions: Action[];          // Array of actions that were executed
}
Each Action in the actions array contains:
interface Action {
  selector: string;      // XPath selector used
  description: string;   // Human-readable description
  method?: string;       // Playwright method used (click, fill, etc.)
  arguments?: string[];  // Arguments passed to the method
}

Usage Examples

Basic Actions

import { Stagehand } from "@stagehand/api";

const stagehand = new Stagehand({
  env: "BROWSERBASE",
  apiKey: process.env.BROWSERBASE_API_KEY,
});

await stagehand.init();
const page = stagehand.context.pages()[0];

await page.goto("https://example.com");

// Click an element
await stagehand.act("click the login button");

// Fill a form field
await stagehand.act("type '[email protected]' in the email field");

// Select from dropdown
await stagehand.act("select 'United States' from the country dropdown");

Using Variables

// Simple variables
await stagehand.act(
  "fill the username field with %username%",
  {
    variables: {
      username: "[email protected]"
    }
  }
);

// Variables with descriptions
await stagehand.act(
  "fill the login form with credentials",
  {
    variables: {
      email: {
        value: "[email protected]",
        description: "User's login email"
      },
      password: {
        value: "secret123",
        description: "User's password"
      }
    }
  }
);

Multi-Page Actions

const page1 = stagehand.context.pages()[0];
const page2 = await stagehand.context.newPage();

await page2.goto("https://example.com/form");

// Perform action on specific page
await stagehand.act(
  "fill the name field with 'John Doe'",
  { page: page2 }
);

Using Pre-observed Actions

// First, observe to preview the action
const [action] = await stagehand.observe(
  "find the submit button"
);

console.log("Will perform:", action.description);

// Later, execute the cached action
await stagehand.act(action);

Handling Results

const result = await stagehand.act("click the submit button");

if (result.success) {
  console.log("Action completed:", result.message);
  console.log("Actions taken:", result.actions);
} else {
  console.error("Action failed:", result.message);
}

With Timeout

try {
  await stagehand.act(
    "click the slow loading button",
    { timeout: 30000 } // 30 seconds
  );
} catch (error) {
  if (error instanceof ActTimeoutError) {
    console.error("Action timed out");
  }
}

Supported Actions

Stagehand supports a wide range of Playwright actions:
  • click - Click on elements
  • fill - Type text into input fields
  • selectOption - Choose from dropdown menus
  • check / uncheck - Toggle checkboxes
  • hover - Hover over elements
  • dragAndDrop - Drag elements to new locations
  • press - Press keyboard keys

Two-Step Actions

For complex interactions (like selecting from a dropdown), act() automatically performs two-step actions:
  1. Opens the dropdown/menu
  2. Selects the desired option
This happens transparently and is reflected in the returned actions array.

Self-Healing

When initialized with selfHeal: true, act() will automatically:
  1. Retry failed actions by re-analyzing the page
  2. Find alternative selectors if the original element is stale
  3. Adapt to dynamic page changes
const stagehand = new Stagehand({
  env: "LOCAL",
  selfHeal: true, // Enable self-healing
});

Error Handling

act() can throw the following errors:
  • ActTimeoutError - Action exceeded the timeout limit
  • Standard errors for other failure cases
Always check the success field in the result:
const result = await stagehand.act("click the button");

if (!result.success) {
  console.error("Failed:", result.message);
  // Handle failure
}

Best Practices

  1. Be specific - Clear instructions lead to better results
    // Good
    await stagehand.act("click the blue 'Submit' button");
    
    // Less specific
    await stagehand.act("click submit");
    
  2. Use variables for sensitive data - Keep credentials out of logs
    await stagehand.act("type %password% in the password field", {
      variables: { password: process.env.PASSWORD }
    });
    
  3. Check results - Always verify actions succeeded
    const result = await stagehand.act("...");
    if (!result.success) {
      // Handle error
    }
    
  4. Use observe() for previewing - Cache and preview actions before execution
    const [action] = await stagehand.observe("find login button");
    // Review action.description
    await stagehand.act(action);
    
  • observe() - Preview actions before executing them
  • extract() - Extract data from the page
  • agent() - Multi-step autonomous automation

Build docs developers (and LLMs) love