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 ? );
Optional URL to navigate to Default: "about:blank"
A Page object for the new tab
activePage()
Get the most recently active page.
const page = context . activePage ();
The active page, or undefined if no pages exist
setActivePage()
Explicitly set which page is considered active.
context . setActivePage ( page );
pages()
Get all top-level pages (tabs) in creation order.
const allPages = context . pages ();
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
Optional argument passed to the script
Set custom HTTP headers for all requests.
await context . setExtraHTTPHeaders ( headers );
Headers to include in all requests
cookies()
Get browser cookies, optionally filtered by URL.
const cookies = await context . cookies ( urls ? );
Optional URL(s) to filter cookies
Array of cookie objects Unix timestamp in seconds (-1 for session cookies)
sameSite
'Strict' | 'Lax' | 'None'
required
addCookies()
Add one or more cookies to the browser.
await context . addCookies ( cookies );
Array of cookies to add Show CookieParam properties
URL to derive domain/path from (provide url OR domain+path)
Unix timestamp in seconds
sameSite
'Strict' | 'Lax' | 'None'
clearCookies()
Clear cookies from the browser.
await context . clearCookies ( options ? );
Optional filters to selectively clear cookies
close()
Close the CDP connection and clean up.
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 ();