Skip to main content

Overview

The V3Context class manages the Chrome DevTools Protocol (CDP) connection and orchestrates page lifecycle. It maintains one Page instance per top-level browser tab and handles iframe (OOPIF) sessions.

Accessing Context

Access the context through the stagehand.context property:
const context = stagehand.context;

Methods

newPage()

Create a new browser tab and return its Page object.
const page = await context.newPage(url?);
url
string
Optional URL to navigate toDefault: "about:blank"
returns
Promise<Page>
A Page object for the new tab

activePage()

Get the most recently active page.
const page = context.activePage();
returns
Page | undefined
The active page, or undefined if no pages exist

setActivePage()

Explicitly set which page is considered active.
context.setActivePage(page);
page
Page
required
The page to make active

pages()

Get all top-level pages (tabs) in creation order.
const allPages = context.pages();
returns
Page[]
Array of all Page objects

addInitScript()

Add a script that runs on every new document before other scripts.
await context.addInitScript(script, arg?);
script
string | Function | { path: string }
required
Script source, function, or file path
arg
any
Optional argument passed to the script

setExtraHTTPHeaders()

Set custom HTTP headers for all requests.
await context.setExtraHTTPHeaders(headers);
headers
Record<string, string>
required
Headers to include in all requests

cookies()

Get browser cookies, optionally filtered by URL.
const cookies = await context.cookies(urls?);
urls
string | string[]
Optional URL(s) to filter cookies
returns
Promise<Cookie[]>
Array of cookie objects

addCookies()

Add one or more cookies to the browser.
await context.addCookies(cookies);
cookies
CookieParam[]
required
Array of cookies to add

clearCookies()

Clear cookies from the browser.
await context.clearCookies(options?);
options
ClearCookieOptions
Optional filters to selectively clear cookies

close()

Close the CDP connection and clean up.
await context.close();

Example

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

const stagehand = new Stagehand({ env: "LOCAL" });
await stagehand.init();

const context = stagehand.context;

// Create multiple pages
const page1 = await context.newPage("https://example.com");
const page2 = await context.newPage("https://github.com");

// Get all pages
const allPages = context.pages();
console.log(`Total pages: ${allPages.length}`);

// Add cookies
await context.addCookies([
  {
    name: "session_id",
    value: "abc123",
    url: "https://example.com",
  },
]);

// Get cookies
const cookies = await context.cookies("https://example.com");
console.log(cookies);

await stagehand.close();

Build docs developers (and LLMs) love