Stagehand
Learn about the main Stagehand object
Clipboard
Learn about reading, writing, copying, cutting, and pasting clipboard text
Overview
Thecontext 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:
Methods
newPage()
Create a new page (tab) in the browser.The URL to navigate to in the new page.Default:
"about:blank"Promise<Page> - The newly created page object.
The new page is automatically set as the active page.
pages()
Get all open pages in the browser context.Page[] - Array of all open pages, ordered from oldest to newest.
activePage()
Get the currently active page.Page | undefined - The most recently used page, or undefined if no pages exist.
The active page is determined by:
- Most recently interacted with page
- Most recently created page if no interaction history
undefinedif all pages have been closed
setActivePage()
Set a specific page as the active page.The page to set as active. Must be a page that exists in this context.
- Marks the page as most recently used
- Brings the tab to the foreground (in headed mode)
- Makes it the default page for subsequent operations
addInitScript()
Inject JavaScript that runs before any page scripts on every navigation.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.
Extra data that is JSON-serialized and passed to your function. Only supported
when
script is a function.- Runs at document start, and installs the script on all currently open pages and replays it on every navigation of those pages
- Automatically applies the same script to any pages created after calling
context.addInitScript() - Allows referencing preload files via
{ path: "./preloads/dom-hooks.js" }, mirroring Playwright’ssourceURLbehavior for readable stack traces
setExtraHTTPHeaders()
Set HTTP headers that will be included in every request made by all pages in the browser context.A plain object of header name–value pairs. All values must be strings.
- 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.setDomainPolicy()
Set a context-wide network domain policy that allows or blocks HTTP(S) requests by hostname.A domain policy with
allowedDomains, blockedDomains, or both.data: and file: are not blocked by this policy.
For newly opened targets, such as popups opened via
window.open(), domain blocking can be race-sensitive. If Stagehand cannot guarantee that a disallowed target was intercepted in time, it closes that target.setDomainPolicy() replaces the previous policy. To clear the policy, pass null, {}, or empty arrays:
- Use
"example.com"for an exact hostname match - Use
"*.example.com"to match subdomains such as"app.example.com"and"deep.app.example.com" "*.example.com"does not match the apex domain"example.com"; include both patterns if you need both- Do not include a scheme, path, port, query string, or fragment
- Matching is case-insensitive, and duplicate normalized patterns are ignored
When both
blockedDomains and allowedDomains are provided, blockedDomains takes precedence. Blocked requests fail with Chrome’s BlockedByClient network error.getDomainPolicy()
Get the currently configured context-wide domain policy.DomainPolicy | null - The active domain policy, or null when no policy is configured.
cookies()
Retrieve browser cookies, optionally filtered by URL(s).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.
Promise<Cookie[]> - Array of cookie objects.
addCookies()
Set one or more cookies in the browser context.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.clearCookies()
Clear cookies from the browser context. Can clear all cookies or selectively filter by name, domain, or path.Filter options to selectively clear cookies. When omitted, all cookies are cleared.
close()
Close the browser context and all associated pages.- Closes the CDP connection
- Cleans up all pages
- Clears all internal mappings
stagehand.close(). You usually don’t need to call this directly.
Properties
clipboard
Access the browser clipboard API for the active page or a specific page.context.clipboard to read and write clipboard text, paste into focused elements, or copy and cut selected content. See the clipboard reference for the full API.
Code Examples
- Basic Usage
- Multi-Page Workflow
- Page Management
- Parallel Operations
- Active Page Tracking
- Custom HTTP Headers
- Domain Policy
Working with Active Pages
The context tracks which page is currently active:Relationship Between Context and Page
- 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
Best Practices
- Create pages explicitly - Use
context.newPage()instead of relying on popups or window.open - Track page references - Store page objects in variables for easier management
- Set active page before operations - Ensure the correct page is active before calling Stagehand methods
- Clean up properly - Call
stagehand.close()to close all pages and the context - Handle page order - Remember that
context.pages()returns pages in creation order - Use parallel operations - Work with multiple pages simultaneously for better performance
Common Patterns
Tab Management
Bulk Data Collection
Conditional Page Management
Error Handling
Context methods may throw the following errors:- 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 afailuresarray with per-session details - StagehandInvalidArgumentError -
setDomainPolicy()received an invalid policy, such as a URL instead of a domain-only pattern - StagehandSetDomainPolicyError -
setDomainPolicy()failed to enable or disable enforcement for one or more sessions. The error includes afailuresarray with per-session details

