Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/browserbase/stagehand/llms.txt

Use this file to discover all available pages before exploring further.

Overview

This page documents the core TypeScript types used throughout the Stagehand API.

Action

Represents an interactive element or action on the page.
interface Action {
  selector: string;
  description: string;
  method?: string;
  arguments?: string[];
}
selector
string
required
Element selector (XPath or CSS)
description
string
required
Human-readable description of the element
method
string
Suggested DOM method to call
arguments
string[]
Suggested method arguments

Variables

Variables for use in actions and agent execution.
type Variables = Record<string, VariableValue>;

type VariableValue =
  | string
  | number
  | boolean
  | { value: string | number | boolean; description?: string };

Examples

// Simple variables
const vars: Variables = {
  email: "user@example.com",
  age: 25,
  subscribed: true,
};

// Rich variables with descriptions
const richVars: Variables = {
  username: {
    value: "john_doe",
    description: "Account username",
  },
  password: {
    value: "secret123",
    description: "Account password",
  },
};

LoadState

Page lifecycle states for navigation waiting.
type LoadState = "load" | "domcontentloaded" | "networkidle";
load
string
Wait until the load event is fired
domcontentloaded
string
Wait until the DOMContentLoaded event is fired (default)
networkidle
string
Wait until there are no more than 0 network connections for at least 500ms

Browser cookie representation.
interface Cookie {
  name: string;
  value: string;
  domain: string;
  path: string;
  expires: number; // Unix timestamp in seconds, -1 for session cookie
  httpOnly: boolean;
  secure: boolean;
  sameSite: "Strict" | "Lax" | "None";
}

CookieParam

Parameters for setting a cookie.
interface CookieParam {
  name: string;
  value: string;
  url?: string; // Provide url OR domain+path
  domain?: string;
  path?: string;
  expires?: number;
  httpOnly?: boolean;
  secure?: boolean;
  sameSite?: "Strict" | "Lax" | "None";
}

ClearCookieOptions

Options for selectively clearing cookies.
interface ClearCookieOptions {
  name?: string | RegExp;
  domain?: string | RegExp;
  path?: string | RegExp;
}

Example

// Clear all cookies with "session" in the name
await context.clearCookies({ name: /session/ });

// Clear cookies from specific domain
await context.clearCookies({ domain: "example.com" });

HistoryEntry

Record of a Stagehand operation.
interface HistoryEntry {
  method: "act" | "extract" | "observe" | "navigate" | "agent";
  parameters: unknown;
  result: unknown;
  timestamp: string; // ISO 8601 format
}

Example

const history = await stagehand.history;
history.forEach((entry) => {
  console.log(`${entry.timestamp}: ${entry.method}`);
  console.log("  Parameters:", entry.parameters);
  console.log("  Result:", entry.result);
});

LogLine

Structured log message.
interface LogLine {
  category: string;
  message: string;
  level: 0 | 1 | 2; // 0=error, 1=info, 2=debug
  auxiliary?: Record<string, { value: unknown; type: string }>;
}

Example

const stagehand = new Stagehand({
  env: "LOCAL",
  logger: (line: LogLine) => {
    if (line.level === 0) {
      console.error(`[${line.category}]`, line.message);
    } else if (line.level === 1) {
      console.log(`[${line.category}]`, line.message);
    }
  },
});

Page Types

import { Page } from "@browserbasehq/stagehand";
import { Page as PlaywrightPage } from "playwright-core";
import { Page as PuppeteerPage } from "puppeteer-core";
import { Page as PatchrightPage } from "patchright-core";

type AnyPage = PlaywrightPage | PuppeteerPage | PatchrightPage | Page;
Stagehand accepts pages from multiple browser automation libraries.

V3FunctionName

Enum for internal function names used in metrics.
enum V3FunctionName {
  ACT = "ACT",
  EXTRACT = "EXTRACT",
  OBSERVE = "OBSERVE",
  AGENT = "AGENT",
}

Response

HTTP response from page navigation.
class Response {
  url(): string;
  status(): number;
  statusText(): string;
  headers(): Record<string, string>;
  ok(): boolean;
  text(): Promise<string>;
  json(): Promise<unknown>;
}

Example

const response = await page.goto("https://api.example.com/data");

if (response) {
  console.log("Status:", response.status());
  console.log("OK:", response.ok());
  
  if (response.ok()) {
    const data = await response.json();
    console.log(data);
  }
}

ConsoleMessage

Browser console message.
class ConsoleMessage {
  type(): string; // 'log', 'warn', 'error', etc.
  text(): string;
  args(): unknown[];
  location(): { url: string; lineNumber: number; columnNumber: number };
}

Example

page.on("console", (message) => {
  console.log(`[${message.type()}]`, message.text());
});

StagehandZodSchema

Type alias for Zod schemas compatible with Stagehand.
import { z } from "zod";

type StagehandZodSchema = z.ZodTypeAny;

Example

import { z } from "zod";

const mySchema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string().email(),
});

const data = await stagehand.extract("Extract user info", mySchema);

Error Types

Stagehand defines several custom error types:
class StagehandNotInitializedError extends Error {}
class StagehandInvalidArgumentError extends Error {}
class StagehandEvalError extends Error {}
class TimeoutError extends Error {}
class PageNotFoundError extends Error {}
class ActTimeoutError extends Error {}
class CookieSetError extends Error {}
class StagehandSetExtraHTTPHeadersError extends Error {}
class CuaModelRequiredError extends Error {}
class MissingEnvironmentVariableError extends Error {}
class StagehandInitError extends Error {}

Example

import {
  Stagehand,
  StagehandNotInitializedError,
  TimeoutError,
} from "@browserbasehq/stagehand";

try {
  await stagehand.act("click button");
} catch (error) {
  if (error instanceof StagehandNotInitializedError) {
    console.error("Stagehand not initialized. Call init() first.");
  } else if (error instanceof TimeoutError) {
    console.error("Operation timed out");
  } else {
    throw error;
  }
}