Stagehand Context

View as Markdown

All Context methods available when using the Stagehand driver.

Access via runtime.browserContext after launching a Stagehand runtime.

Every method below is a remote call. The SDK translates it into a structured step sent to a single endpoint:

POST /v1/workspaces/{workspaceId}/execute
1{
2 "runtime": "my-browser",
3 "steps": [
4 {
5 "call": "context.goto",
6 "args": ["https://example.com"]
7 }
8 ]
9}

The call field maps directly to the method name. args is a JSON array of the method’s arguments. You can batch multiple steps in one request.

Lifecycle

newPage(url?)

Create a new page (tab) in the browser.

The new page is automatically set as the active page. Defaults to “about:blank” if no URL is provided.

1const page = await context.newPage();
ParameterTypeRequiredDescription
urlstringNoThe URL to navigate to in the new page.

Returns RemoteStagehandPage

Upstream docs


pages()

Get all open pages in the browser context.

Returns an array of all open pages, ordered from oldest to newest.

1const allPages = await context.pages();

Returns RemoteStagehandPage[]

Upstream docs


close()

Close the browser context and all associated pages.

This method:

  • Closes the CDP connection
  • Cleans up all pages
  • Clears all internal mappings

Note: This is typically called internally by stagehand.close(). You usually don’t need to call this directly.

1await runtime.browserContext.close();

Upstream docs


Other

activePage()

Get the currently active page.

The active page is determined by:

  1. Most recently interacted with page
  2. Most recently created page if no interaction history
  3. undefined if all pages have been closed
1const page = await context.activePage();

Returns RemoteStagehandPage \| undefined

Upstream docs


setActivePage(pageId)

Set a specific page as the active page.

This method:

  • Marks the page as most recently used
  • Brings the tab to the foreground (in headed mode)
  • Makes it the default page for subsequent operations

Note: Pass page.id from a RemoteStagehandPage instance.

1context.setActivePage(page.id);
ParameterTypeRequiredDescription
pageIdstringYesThe ID of the page to set as active.

Upstream docs


addInitScript(script, arg?)

Inject JavaScript that runs before any page scripts on every navigation.

This method:

  • Runs at document start
  • Installs the script on all currently open pages
  • Replays it on every navigation of those pages
  • Automatically applies to any pages created after calling addInitScript()
1await context.addInitScript(() => {
2 window.alert = () => {};
3 window.confirm = () => true;
4});
ParameterTypeRequiredDescription
scriptstring | { path?: string; content?: string } | ((arg: Arg) => unknown)YesThe script to inject. Can be raw source code, a file reference, or a function.
argArgNoExtra data that is JSON-serialized and passed to your function.

Upstream docs