The context object manages the browser context, which is a container for multiple pages (tabs). It provides methods for creating new pages, accessing existing pages, and managing which page is currently active.Access the context through your Stagehand instance:
Provide the script to inject. Pass raw source code, reference a file on disk,
or supply a function that Stagehand serializes before sending to the browser.
A plain object of header name–value pairs. All values must be strings.
This method:
Applies the headers to all existing pages in the context immediately
Automatically applies the same headers to any pages created after calling setExtraHTTPHeaders()
Calling it again replaces all previously set extra headers (it does not merge)
To clear all extra headers, pass an empty object: await context.setExtraHTTPHeaders({})
Headers set via context.setExtraHTTPHeaders() are context-wide. They apply to every network request from every page in the context, including navigation requests, XHR/fetch calls, and subresource loads.
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Set custom headers for all requestsawait context.setExtraHTTPHeaders({ "X-Custom-Token": "my-secret-token", "Accept-Language": "en-US",});// All subsequent requests from any page in this context// will include these headersconst page = await context.newPage("https://example.com");
A single URL or array of URLs to filter cookies by. When provided, only cookies that match the domain, path, and secure requirements of the given URLs are returned.Default: Returns all cookies when omitted.
Returns:Promise<Cookie[]> - Array of cookie objects.
Copy
Ask AI
// Get all cookiesconst allCookies = await context.cookies();// Get cookies for a specific URLconst siteCookies = await context.cookies("https://example.com");// Get cookies for multiple URLsconst cookies = await context.cookies([ "https://example.com", "https://api.example.com",]);
Array of cookie parameters to set. Each cookie must provide either url or both domain and path — providing both url and domain (or url and path) will throw a validation error.
Cookies set via context.addCookies() are shared across all pages in the context, scoped by domain and path.
Copy
Ask AI
// Set a cookie using a URLawait context.addCookies([ { name: "session", value: "abc123", url: "https://example.com", },]);// Set a cookie using domain and pathawait context.addCookies([ { name: "token", value: "xyz789", domain: ".example.com", path: "/", secure: true, httpOnly: true, sameSite: "Strict", },]);
Setting sameSite: "None" requires secure: true. Stagehand will throw a validation error if this requirement is not met.
Match cookies by path. Supports exact string match or RegExp.
Copy
Ask AI
// Clear all cookiesawait context.clearCookies();// Clear cookies by exact nameawait context.clearCookies({ name: "session" });// Clear cookies by domain patternawait context.clearCookies({ domain: /\.example\.com$/ });// Combine filters (a cookie must match ALL provided filters to be cleared)await context.clearCookies({ name: "token", domain: ".example.com",});
import { Stagehand } from "@browserbasehq/stagehand";// Initialize with Browserbase (API key and project ID from environment variables)// Set BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID in your environmentconst stagehand = new Stagehand({ env: "BROWSERBASE" });await stagehand.init();const context = stagehand.context;// Create a new pageconst page1 = await context.newPage("https://example.com");console.log("Created page 1");// Create another pageconst page2 = await context.newPage("https://another-site.com");console.log("Created page 2");// Get all pagesconst allPages = context.pages();console.log(`Total pages: ${allPages.length}`);await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Start with main pageconst mainPage = context.pages()[0];await mainPage.goto("https://example.com");// Open additional pagesconst dashboardPage = await context.newPage("https://example.com/dashboard");const settingsPage = await context.newPage("https://example.com/settings");// Work with specific pagecontext.setActivePage(dashboardPage);await stagehand.act("click the export button");// Switch to another pagecontext.setActivePage(settingsPage);await stagehand.act("enable notifications");// Back to main pagecontext.setActivePage(mainPage);await stagehand.act("click the logout button");await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Create multiple pagesconst pages = await Promise.all([ context.newPage("https://site1.com"), context.newPage("https://site2.com"), context.newPage("https://site3.com"),]);console.log(`Opened ${pages.length} pages`);// Get the active pageconst active = context.activePage();console.log(`Active page URL: ${active?.url()}`);// Iterate through all pagesfor (const page of context.pages()) { console.log(`Page URL: ${page.url()}`); console.log(`Page title: ${await page.title()}`);}await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";import { z } from "zod";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Create pages for different sitesconst page1 = await context.newPage("https://site1.com");const page2 = await context.newPage("https://site2.com");const page3 = await context.newPage("https://site3.com");const schema = z.object({ title: z.string(), description: z.string()});// Extract data from all pages in parallelconst results = await Promise.all([ stagehand.extract("get page info", schema, { page: page1 }), stagehand.extract("get page info", schema, { page: page2 }), stagehand.extract("get page info", schema, { page: page3 })]);console.log("Extracted data:", results);await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Create pagesconst homePage = await context.newPage("https://example.com");const aboutPage = await context.newPage("https://example.com/about");const contactPage = await context.newPage("https://example.com/contact");// The last created page (contactPage) is now activeconsole.log("Active:", context.activePage()?.url());// Output: "https://example.com/contact"// Switch to home pagecontext.setActivePage(homePage);console.log("Active:", context.activePage()?.url());// Output: "https://example.com"// Now act on the active page (homePage)await stagehand.act("click the header link");await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;// Set authorization headers for all requestsawait context.setExtraHTTPHeaders({ Authorization: "Bearer my-api-token",});// Navigate — the headers are sent with every requestconst page = context.pages()[0];await page.goto("https://api.example.com/dashboard");// Headers also apply to new pagesconst page2 = await context.newPage("https://api.example.com/settings");// Replace headers (previous headers are removed)await context.setExtraHTTPHeaders({ Authorization: "Bearer refreshed-token", "X-Request-Id": "abc-123",});await stagehand.close();
Copy
Ask AI
import { Stagehand } from "@browserbasehq/stagehand";const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();const context = stagehand.context;const page = context.pages()[0];await page.goto("https://example.com");// Set authentication cookiesawait context.addCookies([ { name: "session_id", value: "abc123", domain: ".example.com", path: "/", httpOnly: true, secure: true, sameSite: "Lax", },]);// Read cookies backconst cookies = await context.cookies("https://example.com");console.log("Cookies:", cookies);// Clear specific cookiesawait context.clearCookies({ name: "session_id" });// Clear all cookiesawait context.clearCookies();await stagehand.close();
The context tracks which page is currently active:
Copy
Ask AI
const stagehand = new Stagehand({ env: "LOCAL" });await stagehand.init();// Get the current active pageconst activePage = stagehand.context.activePage();// Create a new page - it becomes activeconst newPage = await stagehand.context.newPage();// Now context.activePage() returns newPageawait newPage.goto("https://example.com");
Context manages the browser-level state and multiple pages
Page represents a single tab/window with content
Creating a new page via context.newPage() automatically sets it as active
You can explicitly control the active page with context.setActivePage()
Use context.activePage() to get the currently active page
Copy
Ask AI
// Get the active pageconst activePage = stagehand.context.activePage();// Or get the first page directlyconst firstPage = stagehand.context.pages()[0];
Timeout errors - newPage() timeout waiting for page to attach
CDP errors - Connection errors with Chrome DevTools Protocol
Invalid page errors - Attempting to set an active page that doesn’t exist in the context
StagehandSetExtraHTTPHeadersError - setExtraHTTPHeaders() failed to apply headers to one or more sessions. The error includes a failures array with per-session details