Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions .changeset/seven-mice-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@browserbasehq/stagehand": patch
---

fix: page.evaluate() now works with scripts injected via context.addInitScript()
21 changes: 21 additions & 0 deletions packages/core/lib/v3/tests/context-addInitScript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,25 @@ test.describe("context.addInitScript", () => {
});
expect(observed).toEqual(payload);
});

test("context.addInitScript installs a function callable from page.evaluate", async () => {
const page = await ctx.awaitActivePage();

await ctx.addInitScript(() => {
// installed before any navigation
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
window.sayHelloFromStagehand = () => "hello from stagehand";
});

await page.goto("https://example.com", { waitUntil: "domcontentloaded" });

const result = await page.evaluate(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
return window.sayHelloFromStagehand();
});

expect(result).toBe("hello from stagehand");
});
});
5 changes: 4 additions & 1 deletion packages/core/lib/v3/understudy/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,10 @@ export class Page {
session: CDPSessionLike,
source: string,
): Promise<void> {
await session.send("Page.addScriptToEvaluateOnNewDocument", { source });
await session.send("Page.addScriptToEvaluateOnNewDocument", {
source: source,
worldName: "v3-world",
});
}

// Replay every previously registered init script onto a newly adopted session.
Expand Down
Loading