Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/merge-extra-http-headers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@browserbasehq/stagehand-extension": patch
"@browserbasehq/stagehand": patch
"@browserbasehq/stagehand-python": patch
---

keep context and page extra HTTP headers together instead of letting one replace the other, and keep context headers on requests from cross-site iframes
6 changes: 3 additions & 3 deletions packages/docs/v4/reference/context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ await browser.context.addInitScript(() => {

## setExtraHTTPHeaders()

Set additional HTTP headers for every page in the context.
Set additional HTTP headers for every page in the context. Headers set on a page are sent along with these, and the page's value wins when both set the same header.

```typescript
await browser.context.setExtraHTTPHeaders({ "x-test": "true" });
Expand Down Expand Up @@ -392,7 +392,7 @@ await browser.context.add_init_script("window.localStorage.clear()")

## set_extra_http_headers()

Set additional HTTP headers for every page in the context.
Set additional HTTP headers for every page in the context. Headers set on a page are sent along with these, and the page's value wins when both set the same header.

```python
await browser.context.set_extra_http_headers({"x-test": "true"})
Expand Down Expand Up @@ -721,7 +721,7 @@ if err := browserContext.AddInitScript(ctx, "window.localStorage.clear()"); err

## SetExtraHTTPHeaders()

Set additional HTTP headers for every page in the context.
Set additional HTTP headers for every page in the context. Headers set on a page are sent along with these, and the page's value wins when both set the same header.

```go
func (c *BrowserContext) SetExtraHTTPHeaders(ctx context.Context, headers ContextSetExtraHTTPHeadersParamsHeaders) error
Expand Down
6 changes: 3 additions & 3 deletions packages/docs/v4/reference/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ await page.addInitScript(() => {

## setExtraHTTPHeaders()

Set additional HTTP headers for this page.
Set additional HTTP headers for this page. These are sent along with the context's headers, and this page's value wins when both set the same header.

```typescript
await page.setExtraHTTPHeaders({ "x-test": "true" });
Expand Down Expand Up @@ -1425,7 +1425,7 @@ await page.add_init_script("window.localStorage.clear()")

## set_extra_http_headers()

Set additional HTTP headers for this page.
Set additional HTTP headers for this page. These are sent along with the context's headers, and this page's value wins when both set the same header.

```python
await page.set_extra_http_headers({"x-test": "true"})
Expand Down Expand Up @@ -2349,7 +2349,7 @@ if err := page.AddInitScript(ctx, "window.localStorage.clear()"); err != nil {

## SetExtraHTTPHeaders()

Set additional HTTP headers for this page.
Set additional HTTP headers for this page. These are sent along with the context's headers, and this page's value wins when both set the same header.

```go
headers := stagehand.PageSetExtraHTTPHeadersParamsHeaders{"x-test": "true"}
Expand Down
8 changes: 7 additions & 1 deletion packages/extension/understudy/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ export class BrowserContext {
public async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void> {
const nextHeaders = { ...headers };
this.extraHttpHeaders = nextHeaders;
for (const page of this.pagesByTarget.values()) {
page.contextExtraHTTPHeaders = nextHeaders;
}

const sessions: CDPSessionLike[] = [];
for (const sessionId of this._sessionInit) {
Expand All @@ -319,9 +322,11 @@ export class BrowserContext {

const results = await Promise.allSettled(
sessions.map(async (session) => {
// Keep each page's own headers on top of the context's.
const owner = session.id ? this.sessionOwnerPage.get(session.id) : undefined;
await session.send("Network.enable");
await session.send("Network.setExtraHTTPHeaders", {
headers: nextHeaders,
headers: owner ? owner.mergedExtraHTTPHeaders() : nextHeaders,
});
}),
);
Expand Down Expand Up @@ -801,6 +806,7 @@ export class BrowserContext {
});
return;
}
page.contextExtraHTTPHeaders = this.extraHttpHeaders ?? {};
this.wireSessionToOwnerPage(sessionId, page);
this.pagesByTarget.set(info.targetId, page);
this.mainFrameToTarget.set(page.mainFrameId(), info.targetId);
Expand Down
31 changes: 27 additions & 4 deletions packages/extension/understudy/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,10 @@ export class Page {
readonly networkManager: NetworkManager;
/** Document-start scripts installed across every session this page owns. */
readonly initScripts: string[] = [];
/** Headers set with page.setExtraHTTPHeaders(). */
extraHTTPHeaders: Record<string, string> = {};
/** Headers set with context.setExtraHTTPHeaders(); the page's own headers win on a clash. */
contextExtraHTTPHeaders: Record<string, string> = {};
private readonly webMCPInvocations = new Map<string, WebMCPInvocationRecord>();
private readonly webMCPResponseSessions = new Map<CDPSessionLike, WebMCPResponseSessionState>();
private readonly webMCPToolSessions = new Map<CDPSessionLike, WebMCPToolSessionState>();
Expand Down Expand Up @@ -484,8 +487,11 @@ export class Page {
}

this.networkManager.trackSession(childSession, networkCapture, childMainFrameId);
if (this.extraHTTPHeaders)
void this.applyExtraHTTPHeadersToSession(childSession, this.extraHTTPHeaders).catch(() => {});
// The context already sent its headers before the child resumed. Only send when there
// is something to add, since an empty set would erase the context's headers.
const extraHTTPHeaders = this.mergedExtraHTTPHeaders();
if (Object.keys(extraHTTPHeaders).length > 0)
void this.applyExtraHTTPHeadersToSession(childSession, extraHTTPHeaders).catch(() => {});

void this.applyInitScriptsToSession(childSession).catch(() => {});

Expand Down Expand Up @@ -1245,6 +1251,23 @@ export class Page {
return this.registry.asProtocolFrameTree(rootMainFrameId);
}

/**
* The headers every session of this page sends: the context's headers with this page's
* own headers on top. Network.setExtraHTTPHeaders replaces the whole set, so both layers
* have to be sent together. Header names are case-insensitive, so a page header also
* replaces a context header whose name differs only in case.
*/
mergedExtraHTTPHeaders(): Record<string, string> {
const pageHeaderNames = new Set(
Object.keys(this.extraHTTPHeaders).map((name) => name.toLowerCase()),
);
const merged: Record<string, string> = {};
for (const [name, value] of Object.entries(this.contextExtraHTTPHeaders)) {
if (!pageHeaderNames.has(name.toLowerCase())) merged[name] = value;
}
return { ...merged, ...this.extraHTTPHeaders };
}

async applyExtraHTTPHeadersToSession(
session: CDPSessionLike,
headers: Record<string, string>,
Expand Down Expand Up @@ -1673,8 +1696,8 @@ export class Page {
* @return void
*/
async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void> {
const headersToSet = { ...headers };
this.extraHTTPHeaders = headersToSet;
this.extraHTTPHeaders = { ...headers };
const headersToSet = this.mergedExtraHTTPHeaders();

// get the session(s) for this page:
const sessions: CDPSessionLike[] = [this.mainSession];
Expand Down
57 changes: 57 additions & 0 deletions packages/sdk-ts/tests/integration/contextExtraHttpHeaders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,60 @@ describe("context.setExtraHTTPHeaders", () => {
await expect(page.locator("body").innerText()).resolves.toBe("yes");
});
});

describe("context.setExtraHTTPHeaders in cross-site iframes", () => {
let fixture: FixtureServer;
let stagehand: Stagehand;
let childFetchHeaders: Record<string, string | string[] | undefined> | undefined;

beforeEach(async () => {
childFetchHeaders = undefined;
fixture = await startFixtureServer({
"/": () => {
const childUrl = new URL("/child", fixture.url);
childUrl.hostname = "child.test";
return `<!doctype html><iframe src="${childUrl.href}"></iframe>`;
},
"/child":
'<!doctype html><button id="child" onclick="fetch(\'/child-fetch\')">Child action</button>',
"/child-fetch": (request) => {
childFetchHeaders = request.headers;
return "ok";
},
});
stagehand = await createStagehand({
browser: {
args: ["--host-resolver-rules=MAP child.test 127.0.0.1", "--site-per-process"],
},
});
});

afterEach(async () => {
await closeStagehand(stagehand);
await fixture.close();
});

// The click runs after Stagehand adopts the iframe's own CDP session, so the fetch
// reflects the headers that session ends up with rather than the pre-adoption ones.
it("applies headers to requests the iframe sends after it loads", async () => {
await stagehand.browser.context.setExtraHTTPHeaders({ "x-stagehand-test": "yes" });
const page = await firstPage(stagehand);
await page.goto(fixture.url);
await page.locator("iframe >> #child").click();

await expect.poll(() => childFetchHeaders).toBeDefined();
expect(childFetchHeaders?.["x-stagehand-test"]).toBe("yes");
});

it("layers page headers on top of context headers in the iframe", async () => {
await stagehand.browser.context.setExtraHTTPHeaders({ "x-stagehand-test": "yes" });
const page = await firstPage(stagehand);
await page.setExtraHTTPHeaders({ "x-page-header": "from-page" });
await page.goto(fixture.url);
await page.locator("iframe >> #child").click();

await expect.poll(() => childFetchHeaders).toBeDefined();
expect(childFetchHeaders?.["x-stagehand-test"]).toBe("yes");
expect(childFetchHeaders?.["x-page-header"]).toBe("from-page");
});
});
56 changes: 56 additions & 0 deletions packages/sdk-ts/tests/integration/pageExtraHttpHeaders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,60 @@ describe("page.setExtraHTTPHeaders", () => {
expect(headers["x-second"]).toBe("yes");
expect(headers["x-first"]).toBeUndefined();
});

it("keeps context headers when page headers are set", async () => {
await stagehand.browser.context.setExtraHTTPHeaders({ "x-context-header": "from-context" });
const page = await firstPage(stagehand);
await page.setExtraHTTPHeaders({ "x-page-header": "from-page" });
await page.goto(fixture.url);

const headers = await page.evaluate<Record<string, string>>(() =>
JSON.parse(document.body.innerText),
);
expect(headers["x-context-header"]).toBe("from-context");
expect(headers["x-page-header"]).toBe("from-page");
});

it("keeps page headers when context headers are set later", async () => {
const page = await firstPage(stagehand);
await page.setExtraHTTPHeaders({ "x-page-header": "from-page" });
await stagehand.browser.context.setExtraHTTPHeaders({ "x-context-header": "from-context" });
await page.goto(fixture.url);

const headers = await page.evaluate<Record<string, string>>(() =>
JSON.parse(document.body.innerText),
);
expect(headers["x-context-header"]).toBe("from-context");
expect(headers["x-page-header"]).toBe("from-page");
});

it("page headers override context headers with the same name", async () => {
await stagehand.browser.context.setExtraHTTPHeaders({
"X-Shared-Header": "from-context",
"x-context-header": "from-context",
});
const page = await firstPage(stagehand);
await page.setExtraHTTPHeaders({ "x-shared-header": "from-page" });
await page.goto(fixture.url);

const headers = await page.evaluate<Record<string, string>>(() =>
JSON.parse(document.body.innerText),
);
expect(headers["x-shared-header"]).toBe("from-page");
expect(headers["x-context-header"]).toBe("from-context");
});

it("clearing page headers keeps context headers", async () => {
await stagehand.browser.context.setExtraHTTPHeaders({ "x-context-header": "from-context" });
const page = await firstPage(stagehand);
await page.setExtraHTTPHeaders({ "x-page-header": "from-page" });
await page.setExtraHTTPHeaders({});
await page.goto(fixture.url);

const headers = await page.evaluate<Record<string, string>>(() =>
JSON.parse(document.body.innerText),
);
expect(headers["x-context-header"]).toBe("from-context");
expect(headers["x-page-header"]).toBeUndefined();
});
});
Loading